Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 119 ยท Getting Started

Maven in Depth

Learn Maven properly - pom.xml anatomy, coordinates, dependency scopes, transitive dependencies and conflicts, the build lifecycle, plugins, profiles and modules.

A real Java project uses dozens of libraries, and each of those libraries uses others. Somebody has to download the right JAR files, put them on the classpath in the right versions, compile your code, run the tests and package the result, the same way on every laptop and every build server. That somebody is your build tool. Apache Maven has done this job since 2004 and is still the most widely used build tool in the Java world. Spring Boot, Jakarta EE and most open-source libraries document their setup in Maven first.

Maven's big idea is convention over configuration. Instead of writing build scripts that say how to build, you describe what your project is in a pom.xml file: its name, its dependencies, its Java version. Maven already knows how to build a standard Java project from that description, using the standard project layout. This lesson covers everything you need to read and maintain real-world POMs: coordinates, dependencies and scopes, transitive dependencies and version conflicts, the lifecycle, plugins, profiles, multi-module builds and the wrapper. The Build Tools lesson of the Java course gives a shorter first look.

A complete, minimal pom.xml

POM stands for Project Object Model. Here is a realistic POM for a small Java 25 application that uses Jackson for JSON and JUnit for tests. Everything else in this lesson is a variation of it.

XML
<?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>

  <!-- Coordinates: who you are -->
  <groupId>com.example</groupId>
  <artifactId>shop-service</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <!-- Values reused below and read by plugins -->
  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jackson.version>2.22.3</jackson.version>
  </properties>

  <!-- What you need -->
  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>6.1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

With this file and code in src/main/java, mvn package downloads Jackson and JUnit (plus everything they need), compiles your code for Java 25, compiles and runs your tests and produces target/shop-service-1.0.0-SNAPSHOT.jar. You did not write a single build step.

Coordinates: naming every artifact

Every library, plugin and project in the Maven world has coordinates that identify it uniquely, written groupId:artifactId:version:

  • groupId: the organization or project family, usually a reversed domain: com.fasterxml.jackson.core, org.junit.jupiter, com.example.
  • artifactId: the module's name: jackson-databind, junit-jupiter, shop-service.
  • version: such as 2.22.3. A version ending in -SNAPSHOT means "work in progress": Maven may download a newer build of the same snapshot later. Release versions never change once published, which is what makes builds reproducible.
  • packaging (default jar) says what the build produces: jar, war for web apps, pom for parent and aggregator projects.

Artifacts are stored in repositories. Maven Central is the default public one. Everything Maven downloads is cached in your local repository, ~/.m2/repository, in folders built from the coordinates: com/fasterxml/jackson/core/jackson-databind/2.22.3/jackson-databind-2.22.3.jar. Companies often run a private repository manager (Nexus, Artifactory) that proxies Central and hosts internal artifacts.

Maven also writes the coordinates into every JAR it builds, under META-INF/maven/. The Jackson JARs on this site's classpath were built that way, so a program can ask them who they are:

Java What a dependency gives you

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.

Three classes, three different JARs: ObjectMapper comes from jackson-databind-2.22.3.jar, JsonParser from jackson-core-2.22.3.jar and @JsonProperty from jackson-annotations-2.22.jar. In the POM above you declared only jackson-databind. The other two arrived because jackson-databind itself depends on them. Those are transitive dependencies, and managing them is Maven's most important job.

Dependency scopes

A dependency's scope says on which classpaths it appears (compiling main code, compiling and running tests, running the application) and whether it is passed on to projects that depend on yours.

Scope Main compile Tests Runtime / packaged Transitive? Typical use
compile (default) yes yes yes yes Libraries your code calls: Jackson, Guava
provided yes yes no no Supplied by the server at runtime: the Servlet API in a WAR, Lombok
runtime no yes yes yes Needed only to run: JDBC drivers, logging backends
test no yes no no JUnit, Mockito, Testcontainers, H2 for tests
import (only in <dependencyManagement> for pom artifacts: imports a BOM, see below)

Two rules prevent most classpath problems. Test libraries always get test scope, so JUnit never ships to production and your production code cannot accidentally import it. JDBC drivers usually get runtime scope, because your code programs against the java.sql interfaces and should never import org.postgresql classes directly:

XML
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.14</version>
  <scope>runtime</scope>
</dependency>

There is also a system scope that points to a JAR file on disk. Avoid it: it breaks on other machines. Install such a JAR into your company repository instead.

Transitive dependencies

When Maven resolves jackson-databind, it downloads its POM, reads its dependencies, then theirs, and so on. Scopes apply at every step: a library's test and provided dependencies are not passed on to you. The jackson-databind JAR contains its own pom.xml, so you can see this directly:

Java Reading jackson-databind's own dependencies

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.

Only two of Jackson's dependencies, jackson-annotations and jackson-core, have compile scope and reach you. The others (JUnit, AssertJ, Mockito and more) are Jackson's own test tools and stay with Jackson. You can also see two real-world POM features: versions written as properties such as ${jackson.version.core}, defined in a parent POM, and versions left out entirely because a parent's <dependencyManagement> supplies them.

Version conflicts and "nearest wins"

Sooner or later two libraries need different versions of the same artifact. A classpath can contain only one, so Maven picks one using dependency mediation:

  1. Nearest definition wins: the version closest to your project in the dependency tree is used. A dependency you declare directly (depth 1) beats any transitive one.
  2. On a tie at the same depth, the first declaration in the POM wins.

Maven does not pick the highest version, which surprises many developers. The following program implements the same algorithm on a made-up set of libraries and prints the result in the format of mvn dependency:tree -Dverbose:

Java How Maven resolves a dependency tree

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.

Read the output from the top:

  • json-lite is wanted in two versions. 2.4 sits at depth 2 (under web-toolkit), 1.9 at depth 3 (under pdf-writer), so 2.4 wins and 1.9 is "omitted for conflict". If pdf-writer really needs 1.9 behavior, you get a runtime error such as NoSuchMethodError, not a compile error. That is classic "dependency hell".
  • http-core:1.8 appears twice in the same version: "omitted for duplicate", no problem.
  • web-toolkit's own test-kit:5.0 never appears: test dependencies are not transitive.
  • assertions comes in through your test dependency, so it gets test scope too.

Try it: add "org.acme:json-lite:1.9 compile" as the first line of PROJECT. Now 1.9 is at depth 1 and beats 2.4. Declaring a dependency directly is the bluntest way to force a version.

Taking control: dependencyManagement, BOMs and exclusions

In real projects you steer resolution with three tools:

XML
<dependencyManagement>
  <dependencies>
    <!-- 1. Pin a version for EVERY occurrence, direct or transitive -->
    <dependency>
      <groupId>org.acme</groupId>
      <artifactId>json-lite</artifactId>
      <version>2.4</version>
    </dependency>

    <!-- 2. Import a BOM: a POM that pins versions for a whole family -->
    <dependency>
      <groupId>com.fasterxml.jackson</groupId>
      <artifactId>jackson-bom</artifactId>
      <version>2.22.3</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <!-- No version needed: the BOM supplies it -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
  </dependency>

  <!-- 3. Exclude a transitive dependency you don't want -->
  <dependency>
    <groupId>org.acme</groupId>
    <artifactId>report-engine</artifactId>
    <version>1.2</version>
    <exclusions>
      <exclusion>
        <groupId>org.acme</groupId>
        <artifactId>pdf-writer</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
</dependencies>

<dependencyManagement> does not add dependencies; it only says "if this artifact shows up anywhere, use this version". A BOM (bill of materials) is a POM full of such entries. Jackson, JUnit, Spring Boot and many cloud SDKs publish BOMs so that all their modules stay in matching versions. Spring Boot's parent POM is essentially one giant BOM, which is why Spring Boot projects rarely write version numbers.

Whenever you suspect a conflict, ask Maven what it actually resolved:

Terminal
mvn dependency:tree                      # the resolved tree
mvn dependency:tree -Dverbose            # include omitted conflicts and duplicates
mvn dependency:tree -Dincludes=org.acme:json-lite   # just one artifact
mvn dependency:analyze                   # used-but-undeclared and declared-but-unused

The build lifecycle

Maven builds follow a fixed sequence of phases. There are three lifecycles: clean (deletes target/), default (builds) and site (generates documentation). The important phases of the default lifecycle, in order:

Phase What happens (for jar packaging)
validate Checks the POM is correct
compile Compiles src/main/java into target/classes (after copying resources)
test Compiles src/test/java and runs unit tests
package Builds the JAR in target/
verify Runs integration tests and quality checks
install Copies the JAR into your local repository ~/.m2, so other local projects can use it
deploy Uploads the JAR to a remote repository

Running a phase runs every phase before it. mvn package validates, compiles, tests and then packages. The most common commands are therefore short:

Terminal
mvn clean verify          # full clean build with all tests: what CI should run
mvn test                  # compile and run unit tests
mvn package -DskipTests   # build the JAR without running tests (compiles them)
mvn test -Dtest=PriceCalculatorTest           # one test class
mvn -pl orders -am verify                     # one module of a multi-module build, plus what it needs
mvn -U clean verify       # force-check remote repositories for updated snapshots
mvn -o verify             # offline: only use ~/.m2

mvn install is rarely what you want. It is only needed when another separate project on your machine must use your JAR. In a multi-module project, mvn verify from the root builds every module together. Habitual install fills ~/.m2 with stale snapshots that later get used by mistake.

Plugins and goals

Phases are just names. The actual work is done by plugins, each offering one or more goals (plugin:goal). The packaging type binds default goals to phases: for jar, compiler:compile runs in compile, surefire:test in test, jar:jar in package. You can also run a goal directly, as you did with dependency:tree.

You configure plugins in <build><plugins>. Always pin plugin versions; otherwise Maven picks defaults that change between Maven releases:

XML
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.16.0</version>
      <configuration>
        <release>25</release>                 <!-- same as the maven.compiler.release property -->
        <compilerArgs><arg>-Xlint:all</arg></compilerArgs>
      </configuration>
    </plugin>

    <!-- Runs unit tests (*Test.java) in the test phase -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.6.0</version>
    </plugin>

    <!-- Runs integration tests (*IT.java) in integration-test/verify -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-failsafe-plugin</artifactId>
      <version>3.6.0</version>
      <executions>
        <execution>
          <goals><goal>integration-test</goal><goal>verify</goal></goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

A few plugins you will meet constantly:

  • maven-compiler-plugin: use release (not the older source/target pair). release also checks that you only use APIs that exist in that Java version.
  • maven-surefire-plugin and maven-failsafe-plugin: unit tests in test, integration tests in verify. Failsafe lets the build finish its cleanup before failing. More in Integration Testing.
  • maven-jar-plugin builds the normal JAR, which does not contain your dependencies. To run it you need them on the classpath.
  • maven-shade-plugin builds an "uber" or "fat" JAR that includes all dependencies, so java -jar app.jar just works. Spring Boot projects use spring-boot-maven-plugin instead, which nests the dependency JARs inside a runnable JAR (Deploying Java Applications).

Profiles

A profile is a named block of POM settings that is switched on only in some situations: by a flag (mvn verify -Pci), a property, the JDK version or the operating system.

XML
<profiles>
  <profile>
    <id>ci</id>
    <build>
      <plugins>
        <plugin>
          <groupId>org.jacoco</groupId>
          <artifactId>jacoco-maven-plugin</artifactId>
          <!-- coverage only on the build server -->
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

Use profiles for build differences (extra checks on CI, a native-image build). Do not use them to bake environment configuration such as database URLs into different JARs; build one artifact and configure it at runtime, as described in the previous lesson.

Multi-module projects

Larger systems split into modules that are built together. A root POM with pom packaging lists the modules and holds shared configuration; each module has its own POM with the root as <parent>:

TEXT
shop/
โ”œโ”€โ”€ pom.xml              (packaging pom: <modules>, <dependencyManagement>, plugin versions)
โ”œโ”€โ”€ shop-domain/pom.xml  (plain Java: entities and rules)
โ”œโ”€โ”€ shop-persistence/pom.xml   (depends on shop-domain)
โ””โ”€โ”€ shop-api/pom.xml     (depends on both; builds the runnable JAR)
XML
<!-- root pom.xml -->
<groupId>com.example.shop</groupId>
<artifactId>shop-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
  <module>shop-domain</module>
  <module>shop-persistence</module>
  <module>shop-api</module>
</modules>

<!-- shop-api/pom.xml -->
<parent>
  <groupId>com.example.shop</groupId>
  <artifactId>shop-parent</artifactId>
  <version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>shop-api</artifactId>
<dependencies>
  <dependency>
    <groupId>com.example.shop</groupId>
    <artifactId>shop-persistence</artifactId>
    <version>${project.version}</version>
  </dependency>
</dependencies>

Maven's reactor reads all modules, sorts them by their dependencies and builds them in the right order. Modules make boundaries explicit: if shop-domain does not depend on shop-persistence, domain code cannot import persistence classes. The compiler enforces your architecture.

The Maven wrapper

Different projects need different Maven versions. The Maven wrapper pins one per project: a small script (mvnw and mvnw.cmd) plus .mvn/wrapper/maven-wrapper.properties, all committed to Git. The first run downloads the declared Maven version; nobody needs Maven installed at all.

Terminal
mvn wrapper:wrapper -Dmaven=3.9.11    # add the wrapper to a project (once)
./mvnw clean verify                   # macOS / Linux
mvnw.cmd clean verify                 # Windows

Use the wrapper in every project, and always in CI. It is the Maven counterpart of pinning plugin versions: the build behaves the same everywhere.

Maven 4 is the next major version. It adds a new POM model version (4.1.0) with conveniences such as automatic module versions and a separate "consumer POM" for publishing, but it still builds 4.0.0 POMs like the ones in this lesson. Everything here applies to both Maven 3.9 and Maven 4.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your project declares library-a, which depends on commons:3.0, and library-b, which depends on helper, which depends on commons:4.0. Which version of commons ends up on the classpath?

    Maven's mediation is "nearest wins", not "highest wins". 3.0 is at depth 2, 4.0 at depth 3. Use dependencyManagement to choose explicitly.
  2. 2. A library you depend on declares mockito-core with test scope. What does that mean for your project?

    As the jackson-databind example showed, test (and provided) dependencies stay with the library that declared them.
  3. 3. You run mvn package. Which phases run?

    Running a phase runs every earlier phase of the same lifecycle. clean belongs to a different lifecycle and only runs if you ask for it.
  4. 4. Which scope should the PostgreSQL JDBC driver normally have?

    The driver is loaded at runtime through JDBC's service mechanism. runtime keeps it off the compile classpath, so no code can depend on driver-specific classes by accident.
  5. 5. What does an entry in <dependencyManagement> do on its own?

    dependencyManagement only manages. You still declare the dependency in <dependencies>, but without a version.

Summary

  • Maven builds from a declarative pom.xml and the standard layout: convention over configuration.
  • Artifacts are identified by coordinates groupId:artifactId:version, stored in repositories (Maven Central, company repositories) and cached in ~/.m2/repository. -SNAPSHOT versions can change; releases never do.
  • Scopes (compile, provided, runtime, test, import) control classpaths and transitivity. Test libraries are test, JDBC drivers runtime.
  • Transitive dependencies are resolved with "nearest wins, then first declared", not "highest wins". Control them with dependencyManagement, BOMs and exclusions, and inspect them with mvn dependency:tree.
  • The lifecycle runs phases in order (validate โ†’ compile โ†’ test โ†’ package โ†’ verify โ†’ install โ†’ deploy); plugins do the work. Pin plugin versions, prefer mvn clean verify, and commit the Maven wrapper.
  • Profiles adjust the build; multi-module projects share a parent POM and let the reactor build modules in dependency order.

Next: Gradle in Depth, the other major Java build tool, with a Kotlin-based build script, task graphs and incremental builds.