Maven Dependencies
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.jarfrom Maven Central into~/.m2/repositoryand adds it to the compile classpath. - The
import com.google.gson.Gsonnow compiles because the JAR is on the classpath. Without the dependency,javacreportspackage 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)istrue.
Maven Dependency Scopes
A scope controls on which classpaths a dependency appears and whether it is passed on to projects that depend on yours.
| Scope | Compile | Test | Packaged / runtime | Typical use |
|---|---|---|---|---|
compile (default) | Yes | Yes | Yes | Libraries your code imports, such as Gson |
provided | Yes | Yes | No, the server supplies it | jakarta.servlet-api in a WAR |
runtime | No | Yes | Yes | JDBC drivers, logging back-ends |
test | No (main code) | Yes | No | JUnit, 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. runtimemeans your code cannotimport org.h2..., which keeps it database-neutral. The driver is still present when the app or the tests run.providedlibraries 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 insrc/main/javafails with "package does not exist", and aprovidedlibrary that the server does not have fails at run time withNoClassDefFoundError.
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 as | Its compile dependency becomes | Its runtime dependency becomes |
|---|---|---|
compile | compile | runtime |
runtime | runtime | runtime |
provided | provided | provided |
test | test | test |
How it works:
- The tree shows the path from your project to each library, so you can see exactly which dependency pulled it in.
providedandtestdependencies of other libraries are never passed on to you. Only theircompileandruntimedependencies 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
groupIdandartifactId, 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:
-Dverbosealso prints the versions Maven threw away and why.- Gson asked for
2.41.0, but your direct declaration is nearer, so2.36.0wins. 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
dependencyConvergencerule, 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.versionproperty 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
dependencyManagementis the cleanest way to fix a version conflict across the whole project.
Useful Maven Dependency Commands
| Command | What it shows or does |
|---|---|
mvn dependency:tree | The full tree with scopes |
mvn dependency:tree -Dincludes=groupId | Only the paths to one library |
mvn dependency:tree -Dverbose | Also omitted and conflicting versions |
mvn dependency:analyze | Declared-but-unused and used-but-undeclared dependencies |
mvn dependency:copy-dependencies | Copies dependency JARs into target/dependency |
mvn versions:display-dependency-updates | Newer versions of your dependencies |
mvn -U package | Re-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, andversions: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:
| Dependency | Scope | Why |
|---|---|---|
| Gson | compile | The main code imports com.google.gson |
| H2 database | runtime | The code only uses java.sql; the driver is needed when the app and tests run |
| JUnit Jupiter | test | Only 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:
- compile scope.
StudentExporterimports Gson, so Gson must be on the compile classpath. Its transitiveerror_prone_annotationscame along automatically, astarget/dependencyshows. - runtime scope. No class imports anything from H2.
DriverManagerfinds the H2 driver on the classpath at run time through Java's service loader, so thejdbc:h2:URL works in both the app and the test. Switching to PostgreSQL would only need a different driver dependency and URL. - test scope. JUnit is only on the test classpath. It is missing from
target/dependencybecause-DincludeScope=runtimecopies onlycompileandruntimelibraries, exactly what the app needs to run. - One place for versions. The
gson.versionandh2.versionproperties and the JUnit BOM keep every version at the top of the POM, ready for the next upgrade. - Correct order.
ORDER BY marks DESCputs 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.