Getting Started with Maven | Maven Quick Start | Adding Dependencies

Edit Maven’s pom.xml and add dependencies, which are Jar files. When dependencies are added, Maven includes those Jars in the build classpath.

This example adds logging-related Jars: slf4j-api and logback-classic.

Step 1. Edit pom.xml

Edit the pom.xml from the previous Encoding and Compiler Settings article and add two dependencies.

my-app/pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.devkuma.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
</project>

Add the two dependencies above the JUnit dependency. Do not change the other parts.

Step 2. Edit the App Class

Edit the App class generated when the project was created.

my-app/src/main/java/com/devkuma/app/App.java

package com.devkuma.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {
  private static final Logger log = LoggerFactory.getLogger(App.class);
  public static void main(String[] args) {
    log.info("Hello!");
    System.out.println("Hello World!");
  }
}

Add the following lines.

  • private static final Logger log...
  • log.info("Hello!");

Step 3. Run the Application

When the application runs, output like the following is displayed.

08 : 07 : 23.818 [main] INFO com.devkuma.app.App - Hello!
Hello World!

The first line is log output produced by slf4j-api and logback-classic.