Sub topic 8
Declaring Dependencies and Scopes in Maven
What a Dependency Is
A dependency is a library your project needs but did not write. One example is Guava, which is a set of helper classes from Google. Another is JUnit, which runs your tests.
You do not download these JAR files yourself. You list them in pom.xml, and Maven fetches them from a repository for you.
Declaring a Dependency
Each dependency goes inside a <dependencies> block. You name it with its coordinates: groupId, artifactId, and version.
<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>This block goes inside <project> in your pom.xml, next to <properties> and <build>. The next time you run mvn compile, Maven downloads Guava. Your code in src/main/java can then import it.
What a Scope Is
A scope tells Maven where a dependency is needed. Some libraries are needed when your code compiles. Some are needed only when tests run. Some are needed only while the program runs.
Maven keeps separate classpaths. A classpath is the list of JAR files Java can see at one step. The scope decides which classpaths a dependency joins.
| Scope | Main code compile | Tests | Runtime | Typical use |
|---|---|---|---|---|
| `compile` (default) | Yes | Yes | Yes | Libraries your code calls, like Guava |
| `test` | No | Yes | No | Test tools, like JUnit |
| `provided` | Yes | Yes | No | APIs the server supplies, like the Servlet API |
| `runtime` | No | Yes | Yes | Drivers loaded at run time, like a JDBC driver |
If you leave out <scope>, Maven uses compile.
Why Scopes Matter
Scopes keep your program small and correct. JUnit has test scope, so it never ends up in your shipped application. If you import a JUnit class in src/main/java by mistake, the compile fails. That failure tells you test code has leaked into main code.
Checking What You Declared
Run this command to see every dependency and its scope:
mvn dependency:treeEach line shows the coordinates, then the scope, for example com.google.guava:guava:jar:33.2.1-jre:compile. The tree can also list libraries you never declared. Those are covered in the chapter on transitive dependencies.
Exercises
Exercise
You add the PostgreSQL JDBC driver. Your code only talks to the standard java.sql interfaces, and the driver is loaded when the program runs. Which scope fits best?
Show answer
runtime. Your code does not need the driver to compile, but the program needs it on the classpath when it runs.
Exercise
A dependency has no <scope> element. Which scope does Maven use, and can your main code import its classes?
Show answer
Maven uses compile, the default. Yes, main code can import its classes, and the library is also available to tests and at runtime.