Maven Dependencies

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 260 of 306

Maven dependencies are the external libraries your Java project uses, such as Gson for JSON or JUnit for tests. You list them in pom.xml, and Maven downloads them, along with the libraries they need, and puts them on the right classpath at the right time.

This lesson shows how to add Maven dependencies, choose a scope, read the dependency tree, remove unwanted transitive libraries, resolve version conflicts, and manage versions in one place with dependencyManagement and BOMs. It ends with a student exporter that uses three dependencies with three different scopes. If pom.xml is new to you, read Maven in Java first.


Add Maven Dependencies to pom.xml

A dependency is identified by its coordinates: groupId, artifactId and version. You can find them on the library's website or by searching Maven Central.

<dependencies>
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.13.2</version>
  </dependency>
</dependencies>
package com.gocourse.catalog;

import com.google.gson.Gson;

public class CourseJson {

    record Course(String code, String title, long priceInPaise) {}

    public static void main(String[] args) {
        Gson gson = new Gson();
        Course course = new Course("JAVA101", "Java Basics", 49_900);

        String json = gson.toJson(course);              // object -> JSON
        Course copy = gson.fromJson(json, Course.class); // JSON -> object

        System.out.println(json);
        System.out.println(copy.equals(course));
    }
}
mvn compile

Output of the program:

{"code":"JAVA101","title":"Java Basics","priceInPaise":49900}
true

How it works:

  • On the first build, Maven downloads gson-2.13.2.jar from Maven Central into ~/.m2/repository and adds it to the compile classpath.
  • The import com.google.gson.Gson now compiles because the JAR is on the classpath. Without the dependency, javac reports package com.google.gson does not exist.
  • Gson converts the record's components to JSON fields and back. Records compare by value, so copy.equals(course) is true.

Maven Dependency Scopes

A scope controls on which classpaths a dependency appears and whether it is passed on to projects that depend on yours.

ScopeCompileTestPackaged / runtimeTypical use
compile (default)YesYesYesLibraries your code imports, such as Gson
providedYesYesNo, the server supplies itjakarta.servlet-api in a WAR
runtimeNoYesYesJDBC drivers, logging back-ends
testNo (main code)YesNoJUnit, Mockito, H2 for tests
import---Only in dependencyManagement, to import a BOM
<dependencies>
  <!-- compile: used by the main code -->
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.13.2</version>
  </dependency>

  <!-- provided: the application server already has it -->
  <dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
  </dependency>

  <!-- runtime: code only uses java.sql, the driver is loaded when the app runs -->
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.4.240</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

Show every dependency and its scope:

mvn dependency:tree

Output:

[INFO] com.gocourse:report-export:jar:1.0.0
[INFO] +- com.google.code.gson:gson:jar:2.13.2:compile
[INFO] |  \- com.google.errorprone:error_prone_annotations:jar:2.41.0:compile
[INFO] +- jakarta.servlet:jakarta.servlet-api:jar:6.1.0:provided
[INFO] \- com.h2database:h2:jar:2.4.240:runtime

How it works:

  • Each line ends with :scope. The first line is your own project.
  • runtime means your code cannot import org.h2..., which keeps it database-neutral. The driver is still present when the app or the tests run.
  • provided libraries are available while compiling, but a WAR file does not include them because Tomcat or another server already does.

Note: A wrong scope causes confusing errors. A test-scoped library used in src/main/java fails with "package does not exist", and a provided library that the server does not have fails at run time with NoClassDefFoundError.


Transitive Dependencies Explained

Libraries have dependencies of their own. Maven adds those transitive dependencies automatically. In the tree above, you declared Gson, and Maven also added error_prone_annotations because Gson's POM lists it.

Find out why a library is in your project with the includes filter:

mvn dependency:tree -Dincludes=com.google.errorprone

Output:

[INFO] com.gocourse:report-export:jar:1.0.0
[INFO] \- com.google.code.gson:gson:jar:2.13.2:compile
[INFO]    \- com.google.errorprone:error_prone_annotations:jar:2.41.0:compile

The scope of a transitive dependency depends on the scope of the dependency that brought it in:

You declared the parent asIts compile dependency becomesIts runtime dependency becomes
compilecompileruntime
runtimeruntimeruntime
providedprovidedprovided
testtesttest

How it works:

  • The tree shows the path from your project to each library, so you can see exactly which dependency pulled it in.
  • provided and test dependencies of other libraries are never passed on to you. Only their compile and runtime dependencies are.

Exclude a Transitive Dependency

If you do not want a transitive library, for example because it clashes with another one, exclude it on the dependency that brings it in.

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.13.2</version>
  <exclusions>
    <exclusion>
      <groupId>com.google.errorprone</groupId>
      <artifactId>error_prone_annotations</artifactId>
    </exclusion>
  </exclusions>
</dependency>
mvn dependency:tree

Output:

[INFO] com.gocourse:report-export:jar:1.0.0
[INFO] +- com.google.code.gson:gson:jar:2.13.2:compile
[INFO] +- jakarta.servlet:jakarta.servlet-api:jar:6.1.0:provided
[INFO] \- com.h2database:h2:jar:2.4.240:runtime

How it works:

  • An exclusion only needs groupId and artifactId, because it removes every version of that library.
  • Exclusions apply only to the path through the dependency where you declare them.
  • Only exclude what you are sure is unused at run time. These annotations are optional for Gson users, but excluding a real runtime dependency causes ClassNotFoundException.

Resolve Dependency Version Conflicts

When two paths bring in different versions of the same library, Maven keeps only one. The rule is "nearest wins": the version closest to your project in the tree is used. If two versions are at the same depth, the one declared first wins.

Declaring a library directly puts it at depth 1, so it always beats a transitive version:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.13.2</version>
</dependency>
<dependency>
  <groupId>com.google.errorprone</groupId>
  <artifactId>error_prone_annotations</artifactId>
  <version>2.36.0</version>
</dependency>
mvn dependency:tree -Dverbose -Dincludes=com.google.errorprone

Output:

[INFO] com.gocourse:report-export:jar:1.0.0
[INFO] +- com.google.code.gson:gson:jar:2.13.2:compile
[INFO] |  \- (com.google.errorprone:error_prone_annotations:jar:2.41.0:compile - omitted for conflict with 2.36.0)
[INFO] \- com.google.errorprone:error_prone_annotations:jar:2.36.0:compile

How it works:

  • -Dverbose also prints the versions Maven threw away and why.
  • Gson asked for 2.41.0, but your direct declaration is nearer, so 2.36.0 wins. Here that is a downgrade, which can break a library that needs newer classes.
  • Use this rule to fix real conflicts (usually by choosing the newer version), not to pin old versions by accident.

Note: Maven does not fail the build on version conflicts by default. Teams that want strict control add the Maven Enforcer plugin with its dependencyConvergence rule, which fails the build when two paths disagree on a version.


Manage Versions With dependencyManagement and BOMs

<dependencyManagement> declares versions without adding the dependencies. Any <dependency> without a <version> then takes it from there. This keeps all versions in one place, which matters most in multi-module projects.

<properties>
  <gson.version>2.13.2</gson.version>
</properties>

<dependencyManagement>
  <dependencies>
    <!-- a single managed version -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${gson.version}</version>
    </dependency>
    <!-- a BOM: imports managed versions for every JUnit artifact -->
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>6.1.3</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId> <!-- version comes from dependencyManagement -->
  </dependency>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId> <!-- version comes from the BOM -->
    <scope>test</scope>
  </dependency>
</dependencies>
mvn dependency:tree -Dincludes=com.google.code.gson

Output:

[INFO] com.gocourse:report-export:jar:1.0.0
[INFO] \- com.google.code.gson:gson:jar:2.13.2:compile

How it works:

  • The gson.version property gives the version a name. Upgrading Gson means changing one line.
  • A BOM (bill of materials) is a POM that only contains dependencyManagement. Importing it with <type>pom</type> and <scope>import</scope> manages the versions of a whole family of artifacts, such as all JUnit modules.
  • Managed versions also apply to transitive dependencies, so dependencyManagement is the cleanest way to fix a version conflict across the whole project.

Useful Maven Dependency Commands

CommandWhat it shows or does
mvn dependency:treeThe full tree with scopes
mvn dependency:tree -Dincludes=groupIdOnly the paths to one library
mvn dependency:tree -DverboseAlso omitted and conflicting versions
mvn dependency:analyzeDeclared-but-unused and used-but-undeclared dependencies
mvn dependency:copy-dependenciesCopies dependency JARs into target/dependency
mvn versions:display-dependency-updatesNewer versions of your dependencies
mvn -U packageRe-checks remote repositories for updates

Check for outdated libraries in a project that still uses Gson 2.12.1:

mvn versions:display-dependency-updates

Output (shortened):

[INFO] The following dependencies in Dependencies have newer versions:
[INFO]   com.google.code.gson:gson ................................ 2.12.1 -> 2.13.2

How it works:

  • dependency: goals come from the Maven Dependency plugin, and versions: goals from the Versions plugin. Maven finds both by prefix, so you do not need to add them to your POM to run them.
  • Read release notes before upgrading. A new major version can change the library's API.

Real-World Example: Maven Dependencies for a Student Exporter

This app reads student results from a database and exports them as pretty-printed JSON. It uses one dependency per scope:

DependencyScopeWhy
GsoncompileThe main code imports com.google.gson
H2 databaseruntimeThe code only uses java.sql; the driver is needed when the app and tests run
JUnit JupitertestOnly the tests use it
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.gocourse</groupId>
  <artifactId>student-export</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <gson.version>2.13.2</gson.version>
    <h2.version>2.4.240</h2.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>6.1.3</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${gson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>${h2.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.6</version>
      </plugin>
    </plugins>
  </build>
</project>
package com.gocourse.export;

public record Student(String name, String course, int marks) {}
package com.gocourse.export;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentExporter {
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /** Reads all students, best marks first, and returns them as JSON. */
    public String exportJson(String jdbcUrl) throws SQLException {
        List<Student> students = new ArrayList<>();
        try (Connection connection = DriverManager.getConnection(jdbcUrl);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(
                     "SELECT name, course, marks FROM students ORDER BY marks DESC")) {
            while (resultSet.next()) {
                students.add(new Student(
                        resultSet.getString("name"),
                        resultSet.getString("course"),
                        resultSet.getInt("marks")));
            }
        }
        return gson.toJson(students);
    }
}
package com.gocourse.export;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class App {
    public static void main(String[] args) throws Exception {
        String jdbcUrl = "jdbc:h2:mem:school;DB_CLOSE_DELAY=-1";

        try (Connection connection = DriverManager.getConnection(jdbcUrl);
             Statement statement = connection.createStatement()) {
            statement.execute("CREATE TABLE students (name VARCHAR(50), course VARCHAR(50), marks INT)");
            statement.execute("""
                    INSERT INTO students VALUES
                        ('Ravi', 'Python', 78),
                        ('Asha', 'Java', 92)""");
        }

        System.out.println(new StudentExporter().exportJson(jdbcUrl));
    }
}
package com.gocourse.export;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.junit.jupiter.api.Test;

class StudentExporterTest {

    @Test
    void exportsStudentsOrderedByMarks() throws Exception {
        String jdbcUrl = "jdbc:h2:mem:export_test;DB_CLOSE_DELAY=-1";
        try (Connection connection = DriverManager.getConnection(jdbcUrl);
             Statement statement = connection.createStatement()) {
            statement.execute("CREATE TABLE students (name VARCHAR(50), course VARCHAR(50), marks INT)");
            statement.execute("INSERT INTO students VALUES ('Meena', 'Go', 55), ('Asha', 'Java', 92)");
        }

        String json = new StudentExporter().exportJson(jdbcUrl);

        Student[] students = new com.google.gson.Gson().fromJson(json, Student[].class);
        assertEquals("Asha", students[0].name());   // 92 comes first
        assertEquals(55, students[1].marks());
    }
}

Build, copy the runtime libraries next to the classes, and run the app:

mvn package
mvn dependency:copy-dependencies -DincludeScope=runtime
ls target/dependency
java -cp "target/classes:target/dependency/*" com.gocourse.export.App

On Windows, use ; instead of : in the -cp value.

Output (Maven log shortened):

[INFO] Running com.gocourse.export.StudentExporterTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
error_prone_annotations-2.41.0.jar
gson-2.13.2.jar
h2-2.4.240.jar
[
  {
    "name": "Asha",
    "course": "Java",
    "marks": 92
  },
  {
    "name": "Ravi",
    "course": "Python",
    "marks": 78
  }
]

How it works:

  1. compile scope. StudentExporter imports Gson, so Gson must be on the compile classpath. Its transitive error_prone_annotations came along automatically, as target/dependency shows.
  2. runtime scope. No class imports anything from H2. DriverManager finds the H2 driver on the classpath at run time through Java's service loader, so the jdbc:h2: URL works in both the app and the test. Switching to PostgreSQL would only need a different driver dependency and URL.
  3. test scope. JUnit is only on the test classpath. It is missing from target/dependency because -DincludeScope=runtime copies only compile and runtime libraries, exactly what the app needs to run.
  4. One place for versions. The gson.version and h2.version properties and the JUnit BOM keep every version at the top of the POM, ready for the next upgrade.
  5. Correct order. ORDER BY marks DESC puts Asha (92) before Ravi (78), and the test checks the same rule with its own private in-memory database.

To understand how -cp and the * wildcard load these JARs, see Java Classpath. To measure how much of this code your tests cover, see Java Code Coverage.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Maven Dependencies and get answers drawn from it.

Signed-in readers only.