Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Dependencies

Adding Dependencies

Learn how the Maven dependency element works, how to find a library on Maven Central, add it to your POM, refresh your IDE and fix missing-dependency errors.

Almost no real Java program is written from scratch. You parse JSON with a library, log with a library, test with a library. Before build tools, you would download a JAR file from a website, copy it into a lib folder and add it to the compiler's classpath by hand. Then you would do the same for every JAR that JAR needed, and keep track of versions in a text file. It worked, barely.

Maven replaces all of that with one idea: you declare what you need, by name and version, and Maven fetches it for you, along with everything it needs in turn. In this lesson you will learn the <dependency> element, how to find the right coordinates, and what happens between typing a line of XML and seeing the library in your code. Later lessons cover scopes, transitive dependencies and version management.

Maven cannot run in your browser, so every mvn command and every pom.xml snippet on this page is read-only. The runnable examples are small Java programs that simulate the ideas (a dependency graph, a missing-package error) using made-up libraries. The stand-ins show the logic. They are not Maven's real code.

The dependency element

Dependencies live in a <dependencies> block directly under <project> in your pom.xml. Each <dependency> is identified by the same three coordinates you met in Coordinates:

XML
<dependencies>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.18.0</version>
  </dependency>
</dependencies>

Read it as: "I need the artifact commons-lang3, published by the group org.apache.commons, in version 3.18.0." After this change, your classes under src/main/java can write import org.apache.commons.lang3.StringUtils; and it will compile. You do not copy any JAR into your project.

From one line of XML to your code

Find Look the library up on Maven Central.
Declare Add a dependency block to the POM.
Download Maven fetches the JAR and its POM.
Classpath The compiler and your tests can now see it.

You write one block. Maven does the rest.

1 / 2

The full element has a few more fields. You will use the first four constantly and the rest occasionally.

Field Default Meaning
groupId, artifactId required Who published it and what it is called.
version required (unless managed) Which release to use.
scope compile On which classpaths the library appears. See Dependency Scopes.
type jar The packaging of the file you want. pom is used for BOMs.
classifier none A variant of the same artifact, such as sources or tests.
optional false Hide this dependency from projects that depend on yours.
exclusions none Transitive libraries to leave out.

The version may be left out only when a parent POM or a BOM manages it, which is the topic of Managing Versions.

Finding the coordinates

Maven downloads libraries from Maven Central, a public repository that nearly every open-source Java library publishes to. You can search it at central.sonatype.com. Type the name of the library (or the name of a class you want, such as StringUtils) and the result page shows a ready-to-copy snippet for Maven, Gradle and other tools.

When you pick a library, check a few things before you paste:

  • Is it maintained? Look at the date of the latest release. A library with its last release in 2014 may still work, but you are adopting its bugs.
  • Is it the right artifact? Big projects publish many artifacts. Jackson alone has jackson-core, jackson-databind, jackson-annotations and dozens of modules. The documentation of the library tells you which one you need.
  • Which version? Take a recent stable release. Avoid names like RC, beta or SNAPSHOT for production code. Do not trust the word LATEST or RELEASE as a version: it makes your build change from one day to the next.
  • Is the license compatible with how you will ship your software?

The version numbers in this tutorial are examples. Always look up the current release when you start a real project.

Adding a library, step by step

Say you want a null-safe way to check whether a string is blank. Here is the whole workflow:

  1. Search Central for commons-lang3 and copy the snippet.
  2. Paste the <dependency> into the <dependencies> block of your pom.xml.
  3. Tell your IDE to reload the Maven project (more on that below).
  4. Use the class:
Java
import org.apache.commons.lang3.StringUtils;

public class Greeter {
    public static String greet(String name) {
        if (StringUtils.isBlank(name)) {
            return "Hello, stranger!";
        }
        return "Hello, " + StringUtils.capitalize(name) + "!";
    }
}

The first time you build after adding the dependency, Maven has to download the library. The console shows it:

TEXT
[INFO] --- compiler:3.14.0:compile (default-compile) @ demo ---
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.18.0/commons-lang3-3.18.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.18.0/commons-lang3-3.18.0.pom (31 kB at 120 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.18.0/commons-lang3-3.18.0.jar
Downloaded from central: ... (667 kB at 2.1 MB/s)

Maven downloads the library's POM first (to learn what it depends on) and then its JAR. Both files are stored in a cache folder on your machine, so the next build does not need the network. You will see exactly where in Repositories and the Local Cache.

A dependency graph stand-in

Your project depends on a library, which depends on other libraries, and so on. That makes the full picture a graph. The program below models a small pretend repository: each entry lists what that library's own POM declares. It then starts from the dependencies you declared and walks the graph, printing something that looks like the output of mvn dependency:tree.

The libraries are invented. Maven's real resolver also handles versions, scopes and conflicts, which you will add in the next lessons. Here the only job is to see that one declared line can pull in several JARs.

Java Walk a dependency graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that log-api appears twice in the tree but only once on the classpath. In real Maven, the same library reached by two paths is included once. What happens when the two paths ask for different versions is the subject of Transitive Dependencies and Mediation.

Telling your IDE

Your IDE reads the POM to know which libraries to put on its own classpath, so it can offer code completion and underline errors. When you edit the pom.xml, it does not always notice at once:

  • IntelliJ IDEA: click the small "Load Maven Changes" icon that appears in the editor, or use the Maven tool window's "Reload All Maven Projects" button. You can also enable auto-import.
  • Eclipse: right-click the project, then Maven, then "Update Project".
  • VS Code: the Java extension pack usually offers a "Maven: update project" prompt; the Java projects view also has a refresh action.

If your code shows red squiggles on a class you just added but the command line mvn compile succeeds, the IDE has simply not reloaded yet. The command line is the source of truth, because the IDE is only mirroring it.

When a dependency is missing

Three different failures look similar at first. Learning to tell them apart saves a lot of time.

1. Resolution fails: Maven cannot find the artifact. You mistyped a coordinate or picked a version that does not exist. The build stops before compiling:

TEXT
[ERROR] Failed to execute goal on project demo: Could not resolve dependencies for project
com.example:demo:jar:1.0: Could not find artifact org.apache.commons:commons-lang:jar:99.0
in central (https://repo.maven.apache.org/maven2)

Check each coordinate letter by letter against Central. A common slip is commons-lang (the old artifact) versus commons-lang3.

2. Compilation fails: the code imports a class that is not on the classpath. You forgot the dependency, or the IDE and the POM disagree:

TEXT
[ERROR] /demo/src/main/java/com/example/Greeter.java:[3,32] package org.apache.commons.lang3 does not exist

The fix is to add the dependency, not to change the import.

3. Runtime fails: ClassNotFoundException or NoClassDefFoundError. The code compiled, but the library is missing when the program runs, usually because the scope hides it at runtime, or because you run the program with a hand-made classpath that lacks the JARs. Dependency Scopes explains the first cause.

The next program simulates the second case. A source file imports packages, a map says which artifact provides each package, and a tiny "compiler" checks the imports against the declared dependencies. Run it, then add the missing dependency to the declared set and run it again.

Java A missing-dependency compile error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Handy commands

These work from the project folder (read-only here):

Terminal
mvn dependency:tree       # print the whole graph, including transitive libraries
mvn dependency:resolve    # download everything and list the resolved artifacts
mvn dependency:sources    # also download -sources jars, so the IDE can show real code
mvn -U compile            # force Maven to re-check remote repositories for updates

dependency:tree is the one you will use most. Whenever a library behaves strangely, ask yourself what is actually on the classpath, and that command answers.

Good habits

  • Declare only what your own code uses directly. Do not copy transitive libraries into your POM "just in case".
  • Pin explicit versions (or let a BOM pin them). Never use LATEST or RELEASE.
  • Keep the dependency list tidy and grouped. A comment above a block explaining why it is there helps the next reader.
  • Prefer the standard library when it does the job. Every dependency is code you must update, audit and ship.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Maven download first when it resolves a new dependency?

    Maven needs the POM to discover the library's own dependencies. It then downloads the JAR and every other artifact in the graph.
  2. 2. Your code imports a class from a library, and the build prints 'package ... does not exist'. What is the most likely fix?

    The compiler cannot see the library, so it is not on the classpath. Declaring the dependency puts it there. LATEST makes builds unpredictable and is not a fix.
  3. 3. mvn compile works on the command line, but your IDE underlines a newly added library in red. What is the likely cause?

    The IDE keeps its own copy of the classpath. Reload or re-import the Maven project and it picks up the change.
  4. 4. Which version value should you avoid in production POMs?

    LATEST (and RELEASE) are resolved when you build, so the same POM can produce different results on different days. Use explicit versions.

Summary

  • A <dependency> names a library by groupId, artifactId and version, and Maven fetches it and everything it needs.
  • Find coordinates on Maven Central, and check maintenance, the right artifact and a recent stable version.
  • Maven downloads the POM and the JAR, then caches both on your machine.
  • Reload your IDE after editing the POM. The command line is the source of truth.
  • "Could not find artifact" means resolution failed, "package does not exist" means compilation failed, and ClassNotFoundException means the runtime classpath is missing something.
  • mvn dependency:tree shows what is really on the classpath.

Next: Dependency Scopes