Maven and Gradle

suggest change

You can compile a small program with javac and run it with java. A real project quickly needs more: third-party libraries and their dependencies, a test run, a jar to ship, the same build on every machine. Maven and Gradle are the two standard build tools that do this for Java.

Both tools:

The difference is in how you describe the build. Maven uses a declarative XML file (pom.xml) and a fixed lifecycle. Gradle uses a build script written in Kotlin (build.gradle.kts) or Groovy (build.gradle) and a graph of tasks you can extend with code.

All examples were run on JDK 25 with Maven 3.9.16 and Gradle 9.8.1.

The standard project layout

Maven introduced this layout and Gradle uses it too, so the same sources build with either tool:

app/
├── pom.xml                  (Maven)
├── build.gradle.kts         (Gradle)
├── settings.gradle.kts      (Gradle)
└── src/
    ├── main/
    │   ├── java/            application code
    │   └── resources/       files copied into the jar (config, templates)
    └── test/
        ├── java/            test code
        └── resources/       test-only resources

Our example application uses the Gson library to print a greeting as JSON:

// src/main/java/com/example/app/App.java
package com.example.app;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class App {
    record Greeting(String name, String message) {
    }

    static Greeting greet(String name) {
        return new Greeting(name, "Hello, " + name + "!");
    }

    public static void main(String[] args) {
        String name = args.length > 0 ? args[0] : "World";
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(greet(name)));
    }
}
// src/test/java/com/example/app/AppTest.java
package com.example.app;

import org.junit.jupiter.api.Test;

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

class AppTest {
    @Test
    void greetsByName() {
        assertEquals("Hello, Ann!", App.greet("Ann").message());
    }
}

Maven

pom.xml

The POM (Project Object Model) describes the project: its coordinates, dependencies and plugins.

<?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.example</groupId>
  <artifactId>app</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <gson.version>2.14.0</gson.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>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.16.0</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.6.0</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.5.1</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

The important parts:

The lifecycle

Maven runs phases of a fixed lifecycle. Asking for a phase runs every phase before it:

Phase What happens
validate checks the POM
compile compiles src/main/java into target/classes
test compiles and runs tests (Surefire plugin)
package creates target/app-1.0.0.jar
verify runs integration tests and checks
install copies the jar into the local repository ~/.m2/repository
deploy uploads the jar to a remote repository

clean is a separate lifecycle that deletes target/. mvn clean package is a common combination.

$ mvn package
[INFO] Building app 1.0.0
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.5.0:resources (default-resources) @ app ---
[INFO] --- compiler:3.16.0:compile (default-compile) @ app ---
[INFO] Compiling 1 source file with javac [debug release 21] to target\classes
[INFO] --- resources:3.5.0:testResources (default-testResources) @ app ---
[INFO] --- compiler:3.16.0:testCompile (default-testCompile) @ app ---
[INFO] Compiling 1 source file with javac [debug release 21] to target\test-classes
[INFO] --- surefire:3.6.0:test (default-test) @ app ---
[INFO] Running com.example.app.AppTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.082 s -- in com.example.app.AppTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- jar:3.5.1:jar (default-jar) @ app ---
[INFO] Building jar: ...\app\target\app-1.0.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Each line like compiler:3.16.0:compile is a plugin goal bound to a phase. All the work is done by plugins; Maven itself only drives the lifecycle. You can also run a goal directly: mvn dependency:tree, mvn exec:java.

The plain jar contains only your classes, not Gson, and has no Main-Class in its manifest, so java -jar target/app-1.0.0.jar doesn't work yet. The next two sections fix that.

Running the application

The exec-maven-plugin runs a main class with the project's classpath. Add it to <build>, next to <pluginManagement>:

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.6.4</version>
        <configuration>
          <mainClass>com.example.app.App</mainClass>
        </configuration>
      </plugin>
    </plugins>
$ mvn -q compile exec:java -Dexec.args=Ann
{
  "name": "Ann",
  "message": "Hello, Ann!"
}

-q (quiet) hides Maven's own logging. exec:java doesn't compile, so compile comes first.

A runnable fat jar

The maven-shade-plugin builds an uber jar (fat jar): your classes plus the classes of all runtime dependencies, with Main-Class set in the manifest. Add it to the same <plugins> section:

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.6.2</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.example.app.App</mainClass>
                </transformer>
              </transformers>
              <filters>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/versions/*/module-info.class</exclude>
                    <exclude>META-INF/MANIFEST.MF</exclude>
                  </excludes>
                </filter>
              </filters>
            </configuration>
          </execution>
        </executions>
      </plugin>

The <execution> binds the shade goal to the package phase, so mvn package now produces the fat jar. The filters drop files that every dependency jar has (module-info.class, the manifest); without them shade prints "overlapping classes" warnings.

$ mvn clean package
$ java -jar target/app-1.0.0.jar Bob
{
  "name": "Bob",
  "message": "Hello, Bob!"
}

The original thin jar is kept as target/original-app-1.0.0.jar. For other ways of packaging see Creating an UberJAR for an application and its dependencies.

Dependency scopes and the dependency tree

A dependency's scope decides on which classpath it ends up:

Scope Compile Test Runtime / packaged Typical use
compile (default) yes yes yes libraries your code uses
provided yes yes no Servlet API, supplied by the server
runtime no yes yes JDBC drivers, logging backends
test no yes no JUnit, Mockito

Dependencies are transitive: if you depend on Gson, you also get what Gson depends on. mvn dependency:tree shows the whole graph:

$ mvn dependency:tree
[INFO] com.example:app:jar:1.0.0
[INFO] +- com.google.code.gson:gson:jar:2.14.0:compile
[INFO] |  \- com.google.errorprone:error_prone_annotations:jar:2.48.0:compile
[INFO] \- org.junit.jupiter:junit-jupiter:jar:6.1.3:test
[INFO]    +- org.junit.jupiter:junit-jupiter-api:jar:6.1.3:test
[INFO]    |  +- org.opentest4j:opentest4j:jar:1.3.0:test
[INFO]    |  +- org.junit.platform:junit-platform-commons:jar:6.1.3:test
[INFO]    |  +- org.apiguardian:apiguardian-api:jar:1.1.2:test
[INFO]    |  \- org.jspecify:jspecify:jar:1.0.0:test
[INFO]    +- org.junit.jupiter:junit-jupiter-params:jar:6.1.3:test
[INFO]    \- org.junit.jupiter:junit-jupiter-engine:jar:6.1.3:test
[INFO]       \- org.junit.platform:junit-platform-engine:jar:6.1.3:test

When two paths bring in different versions of the same library, Maven picks the one nearest to your project in the tree (and the first declared one on a tie). To force a version, declare it in <dependencyManagement>. To drop a transitive dependency, use <exclusions>:

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${gson.version}</version>
      <exclusions>
        <exclusion>
          <groupId>com.google.errorprone</groupId>
          <artifactId>error_prone_annotations</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

Gradle

settings.gradle.kts and build.gradle.kts

A Gradle build has a settings file that names the project (and lists subprojects) and a build script per project. The Kotlin DSL (.kts) is the default for new projects; it gives you code completion and type checking in the IDE.

// settings.gradle.kts
rootProject.name = "app"

Dependency versions usually live in a version catalog, gradle/libs.versions.toml, which Gradle picks up automatically:

[versions]
gson = "2.14.0"
junit = "6.1.3"

[libraries]
gson = { module = "com.google.code.gson:gson", version.ref = "gson" }
junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" }
junit-launcher = { module = "org.junit.platform:junit-platform-launcher" }

Every library becomes a type-safe accessor: junit-jupiter is libs.junit.jupiter in the build script.

// build.gradle.kts
plugins {
    application
}

group = "com.example"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation(libs.gson)

    testImplementation(platform(libs.junit.bom))
    testImplementation(libs.junit.jupiter)
    testRuntimeOnly(libs.junit.launcher)
}

tasks.withType<JavaCompile>().configureEach {
    options.release = 21
    options.encoding = "UTF-8"
}

application {
    mainClass = "com.example.app.App"
}

tasks.test {
    useJUnitPlatform()
}

Tasks

Gradle works with tasks that depend on each other. gradle build runs everything needed to build and check the project:

$ gradle build --console=plain
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :jar
> Task :startScripts
> Task :distTar
> Task :distZip
> Task :assemble
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
> Task :check
> Task :build

BUILD SUCCESSFUL in 29s
7 actionable tasks: 7 executed

Run it a second time without changes and every task is skipped:

> Task :compileJava UP-TO-DATE
...
> Task :test UP-TO-DATE
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE

BUILD SUCCESSFUL in 9s
7 actionable tasks: 7 up-to-date

Gradle tracks the inputs and outputs of each task and only re-runs tasks whose inputs changed. This incremental build, together with the long-running Gradle daemon and the optional build cache, is why Gradle is usually faster than Maven on larger projects. (In CI, or when you don't want a background process, pass --no-daemon.)

gradle tasks lists the available tasks. The most common ones:

Command What it does
gradle build compile, test, run checks and assemble
gradle test run tests only
gradle test --tests 'com.example.app.AppTest' run one test class
gradle run --args="Ann" run the application
gradle installDist create build/install/app with start scripts and lib/
gradle clean delete build/
gradle dependencies print the dependency tree
$ gradle -q run --args="Ann"
{
  "name": "Ann",
  "message": "Hello, Ann!"
}

installDist (from the application plugin) is often a better way to ship an app than a fat jar. It puts each dependency jar in lib/ and generates start scripts for Unix and Windows that set up the classpath:

build/install/app/bin/app
build/install/app/bin/app.bat
build/install/app/lib/app-1.0.0.jar
build/install/app/lib/error_prone_annotations-2.48.0.jar
build/install/app/lib/gson-2.14.0.jar
$ gradle installDist
$ build/install/app/bin/app Carol
{
  "name": "Carol",
  "message": "Hello, Carol!"
}

Dependency configurations

Gradle's equivalent of scopes are configurations:

Gradle Maven scope Meaning
implementation compile needed to compile and run; not exposed to consumers of a library
api (needs java-library) compile like implementation, but part of your public API, so consumers get it on their compile classpath too
compileOnly provided compile classpath only
runtimeOnly runtime runtime classpath only
testImplementation test compile and run tests
testRuntimeOnly test test runtime only, e.g. the JUnit launcher

The split between api and implementation has no Maven equivalent. Using implementation keeps a library's internals off its users' compile classpath, so changing them doesn't force consumers to recompile.

$ gradle -q dependencies --configuration runtimeClasspath
------------------------------------------------------------
Root project 'app'
------------------------------------------------------------

runtimeClasspath - Runtime classpath of source set 'main'.
\--- com.google.code.gson:gson:2.14.0
     \--- com.google.errorprone:error_prone_annotations:2.48.0

Unlike Maven's "nearest wins", Gradle resolves conflicts by picking the highest requested version.

A custom task: a fat jar

A build script is code, so adding a task doesn't need a plugin. This task builds a fat jar like the shade plugin above:

tasks.register<Jar>("fatJar") {
    group = "build"
    description = "Assembles a jar with all runtime dependencies."
    archiveClassifier = "all"
    manifest {
        attributes("Main-Class" to application.mainClass)
    }
    from(sourceSets.main.get().output)
    from(configurations.runtimeClasspath.map { cp -> cp.map { zipTree(it) } })
    exclude("META-INF/versions/*/module-info.class", "META-INF/*.SF", "META-INF/*.RSA")
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
$ gradle fatJar
$ java -jar build/libs/app-1.0.0-all.jar Bob
{
  "name": "Bob",
  "message": "Hello, Bob!"
}

tasks.register creates the task lazily, only when it's needed. Gradle knows that fatJar needs the compiled classes because its input is sourceSets.main.get().output, so it runs compileJava first. For bigger projects, the Shadow plugin (com.gradleup.shadow) also handles merging service files and relocating packages.

Multi-module projects

Larger codebases are split into modules, for example a core library and an app that uses it.

Maven uses a parent POM with pom packaging that lists the modules. Child POMs inherit its properties and plugin configuration:

<!-- pom.xml -->
<project ...>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>parent</artifactId>
  <version>1.0.0</version>
  <packaging>pom</packaging>

  <modules>
    <module>core</module>
    <module>app</module>
  </modules>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>
<!-- app/pom.xml -->
<project ...>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.example</groupId>
    <artifactId>parent</artifactId>
    <version>1.0.0</version>
  </parent>
  <artifactId>app</artifactId>

  <dependencies>
    <dependency>
      <groupId>com.example</groupId>
      <artifactId>core</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>

core/pom.xml is the same without the <dependencies>. Running mvn package in the root directory builds the modules in dependency order (the reactor):

[INFO] Reactor Summary for parent 1.0.0:
[INFO]
[INFO] parent ............................................. SUCCESS [  0.002 s]
[INFO] core ............................................... SUCCESS [  6.768 s]
[INFO] app ................................................ SUCCESS [  0.246 s]

mvn package -pl app -am builds only app and the modules it depends on ("also make").

Gradle lists subprojects in the settings file, and a project dependency is project(":name"):

// settings.gradle.kts
rootProject.name = "parent"
include("core", "app")
// core/build.gradle.kts
plugins {
    `java-library`
}
// app/build.gradle.kts
plugins {
    application
}

dependencies {
    implementation(project(":core"))
}

application {
    mainClass = "com.example.app.Main"
}
$ gradle -q :app:run
Hello, modules!

:app:run runs the run task of the app project only, building core first. Common configuration shared by subprojects is best put in a convention plugin in buildSrc/ rather than copied into each build script.

The wrapper

Don't rely on whatever Maven or Gradle version is installed on a machine. Both tools have a wrapper: a small script committed to the repository that downloads and runs the exact version the project specifies.

$ mvn wrapper:wrapper -Dmaven=3.9.16
$ ./mvnw package               # mvnw.cmd on Windows

$ gradle wrapper --gradle-version 9.8.1
$ ./gradlew build              # gradlew.bat on Windows

The Maven wrapper creates mvnw, mvnw.cmd and .mvn/wrapper/maven-wrapper.properties. The Gradle wrapper creates gradlew, gradlew.bat, gradle/wrapper/gradle-wrapper.jar and gradle/wrapper/gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip

Commit all of these files. After that, a fresh clone only needs a JDK. gradle init creates a new project that already includes the wrapper and a version catalog. See Testing in CI for using the wrapper on a CI server.

Maven vs Gradle

Maven Gradle
Build file pom.xml (XML) build.gradle.kts (Kotlin) or build.gradle (Groovy)
Model fixed lifecycle of phases, plugins bind goals to phases graph of tasks, any task can depend on any other
Output directory target/ build/
Customization configure plugins; custom logic needs writing a plugin write code directly in the build script or buildSrc
Version conflicts nearest declaration wins highest version wins
Speed rebuilds each module completely incremental tasks, daemon, build cache
Local repository ~/.m2/repository ~/.gradle/caches (can also read mavenLocal())
Used by most enterprise and library projects Android (required), Kotlin, Spring Boot (both supported)

Rules of thumb:

Both publish to and consume from the same repositories, so a library built with one is usable from the other.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents