Sub topic 8
Declaring Dependencies and Scopes in Maven
Real Java programs rarely use only their own code. They also use libraries other people wrote, such as a testing framework or a set of helper classes. A dependency is a library your project needs in order to compile, run, or test. In this chapter you will add dependencies to a pom.xml, choose the right scope for each one, and check what Maven did with them.
What a Dependency Declaration Looks Like
A dependency declaration is a short block of XML inside the <dependencies> section of your pom.xml. It names the library by its coordinates. Coordinates are the groupId, artifactId, and version that identify one exact library. You met them in an earlier chapter.
Here is the smallest useful declaration:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.2.1-jre</version>
</dependency>When Maven reads this block, it does three things:
- It looks for the library in your local cache. The cache is the
~/.m2/repositoryfolder on your computer. - If the library is not in the cache, Maven downloads it from a remote repository such as Maven Central.
- It puts the library's JAR file on the right classpath. A classpath is the list of places Java searches for classes.
You never download a JAR by hand or type a long -cp option. The declaration takes care of both.
Adding a Library to the Example Project
Start from the hello project from the earlier chapters. Add Guava next to JUnit in the <dependencies> section of pom.xml:
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.2.1-jre</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
</dependencies>Now use Guava in src/main/java/com/example/App.java:
package com.example;
import com.google.common.base.Strings;
public class App {
public static void main(String[] args) {
System.out.println(Strings.repeat("=", 15));
System.out.println(greeting("World"));
System.out.println(Strings.repeat("=", 15));
}
static String greeting(String name) {
return "Hello, " + name + "!";
}
}Build the project:
mvn compileThe compile step succeeds because Maven placed Guava on the compile classpath. If you remove the Guava block and compile again, you get the error package com.google.common.base does not exist.
What Is a Scope?
A scope tells Maven when a dependency is needed. Some libraries are needed everywhere. Others are needed only for tests, or only while the program runs. You set the scope with a <scope> element. If you leave it out, Maven uses compile.
Maven keeps separate classpaths for different jobs:
- The main compile classpath is used to compile
src/main/java. - The test classpath is used to compile and run
src/test/java. - The runtime classpath is used when the finished program runs.
Each scope adds the library to some of these classpaths and leaves it off the others.
The Four Scopes You Will Use
| Scope | Compile main code | Compile and run tests | Needed when the program runs | Typical example |
|---|---|---|---|---|
| `compile` (default) | Yes | Yes | Yes | Guava, Jackson |
| `provided` | Yes | Yes | No, the server supplies it | Servlet API, Lombok |
| `runtime` | No | Yes | Yes | A JDBC database driver |
| `test` | No | Yes | No | JUnit, Mockito |
compile
compile is the default scope. Use it for libraries your main code imports and calls directly. Guava in the example above is a compile dependency.
test
test is for libraries that only your tests use. JUnit is the classic case. Your main code cannot import a test library. If App.java tried to import org.junit.jupiter.api.Test, the compile step would fail. This rule stops testing code from leaking into the program you ship.
runtime
runtime is for libraries your code never names directly but which must be present when the program runs. A database driver is the usual example. Your code talks to the standard java.sql interfaces, and the driver is found while the program runs.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
<scope>runtime</scope>
</dependency>provided
provided means "I need this to compile, but something else will supply it when the program runs." A web server such as Tomcat already contains the Servlet API. If you packaged your own copy as well, the two copies could clash.
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>Running a Program That Has Dependencies
Packaging the project shows something that surprises many beginners:
mvn package
java -cp target/hello-1.0-SNAPSHOT.jar com.example.AppThe second command fails with NoClassDefFoundError: com/google/common/base/Strings. A plain Maven JAR contains only your classes. Guava is still sitting in the local cache, outside the JAR.
To run the program, copy the runtime dependencies next to it and add them to the classpath:
mvn dependency:copy-dependencies -DincludeScope=runtime
java -cp "target/hello-1.0-SNAPSHOT.jar:target/dependency/*" com.example.AppOn Windows, use ; instead of : to separate the classpath entries. The -DincludeScope=runtime option copies the compile and runtime libraries and skips the test and provided ones. That is exactly the set the running program needs. A later chapter on plugins shows how to bundle everything into one runnable JAR.
Checking What Maven Resolved
You can always ask Maven which dependencies it found and what scope each one has:
mvn dependency:treeThe output looks like this:
[INFO] com.example:hello:jar:1.0-SNAPSHOT
[INFO] +- com.google.guava:guava:jar:33.2.1-jre:compile
[INFO] | +- com.google.guava:failureaccess:jar:1.0.2:compile
[INFO] | ...
[INFO] \- org.junit.jupiter:junit-jupiter:jar:5.10.2:test
[INFO] ...The last word on each line is the scope. The indented lines are libraries that Guava and JUnit need in turn. Those are called transitive dependencies, and they get their own chapter later.
Keeping Versions in One Place
When several dependencies share a version, store the version once as a property:
<properties>
<junit.version>5.10.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>Maven replaces ${junit.version} with 5.10.2. To upgrade, you change one line.
Common Mistakes
- Forgetting
<scope>test</scope>on JUnit. The build still works, but JUnit ends up on the runtime classpath and gets shipped with your program. - Marking a library
testand then importing it in main code. The compile step fails with "package does not exist". Change the scope tocompile. - Using
providedfor an ordinary library. The code compiles, but it crashes when it runs because nothing supplies the library. - Leaving out
<version>. In a simple project Maven stops with an error sayingdependencies.dependency.versionis missing.
Exercise
Your app uses the H2 database driver only through java.sql.DriverManager and never imports any org.h2 class. Which scope should the com.h2database:h2 dependency use, and why?
Show answer
Use runtime. Your main code never names an H2 class, so the driver isn't needed to compile. It must still be on the classpath when the program runs so that DriverManager can find it.
Exercise
You add Mockito with no <scope> element and the build succeeds. What scope did Maven use, and what is the problem?
Show answer
Maven used the default compile scope. Mockito is now on the main compile and runtime classpaths, so main code could accidentally import it and it would ship with the application. Add <scope>test</scope>.
Exercise
After mvn package, running java -cp target/hello-1.0-SNAPSHOT.jar com.example.App throws NoClassDefFoundError for a Guava class. Explain the cause and give one way to fix it.
Show answer
The JAR holds only the project's own classes, so Guava is not on the classpath. Run mvn dependency:copy-dependencies -DincludeScope=runtime, then start the program with java -cp "target/hello-1.0-SNAPSHOT.jar:target/dependency/*" com.example.App.