Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 119 ยท Getting Started

Gradle in Depth

Learn Gradle for Java - build.gradle.kts, plugins, implementation vs api and other configurations, version catalogs, tasks, incremental builds, the wrapper and Maven vs Gradle.

Gradle is the other major Java build tool. It downloads dependencies from the same Maven repositories, uses the same src/main/java layout and the same groupId:artifactId:version coordinates you learned in Maven in Depth. The difference is in how a build is described and executed. Instead of an XML model with a fixed lifecycle, Gradle builds are code (a Kotlin or Groovy script) that configures a graph of tasks, and Gradle runs only the tasks whose inputs have changed.

That design makes Gradle fast and very flexible, and it is the standard build tool for Android and for many large companies. It also makes builds easier to over-engineer. This lesson teaches the modern, conventional way: the Kotlin DSL (build.gradle.kts), plugins, dependency configurations such as implementation and api, version catalogs, tasks and the task graph, incremental builds, the wrapper, and a fair comparison with Maven. Three runnable models show what Gradle does internally.

A complete build.gradle.kts

A Gradle project has a settings file that names the project (and its modules), and a build script per project. Here is the Gradle equivalent of the Maven POM from the previous lesson: a Java 25 application using Jackson and JUnit.

Kotlin
// settings.gradle.kts
rootProject.name = "shop-service"
Kotlin
// build.gradle.kts
plugins {
    application                      // adds the java plugin, plus 'run' and distribution tasks
}

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

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(25)   // compile and test with a JDK 25
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.fasterxml.jackson.core:jackson-databind:2.22.3")
    runtimeOnly("org.postgresql:postgresql:42.7.14")

    testImplementation("org.junit.jupiter:junit-jupiter:6.1.3")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

application {
    mainClass = "com.example.shop.ShopApplication"
}

tasks.test {
    useJUnitPlatform()               // run tests with JUnit Jupiter
}

From the project folder, ./gradlew build compiles, tests and packages the project into build/libs/shop-service-1.0.0-SNAPSHOT.jar, and ./gradlew run starts the application. Output goes to build/ instead of Maven's target/.

A few lines deserve a closer look:

  • plugins { application } applies a core plugin. Plugins add tasks, conventions and configurations. java adds compilation, testing and JAR tasks; java-library adds the api configuration for libraries; application adds run and start scripts. Community plugins are applied by ID and version: id("org.springframework.boot") version "4.0.0".
  • The toolchain declares which JDK compiles and tests the code, independently of the JDK that runs Gradle itself. If that JDK is missing, Gradle can locate it on the machine or, with a toolchain resolver plugin in settings.gradle.kts, download it.
  • testRuntimeOnly("org.junit.platform:junit-platform-launcher") is required since Gradle 9 when tests run on the JUnit Platform. Without it, test fails with an error about a missing launcher.

Kotlin or Groovy? Older projects use build.gradle in Groovy (implementation 'group:artifact:version'). New projects should use the Kotlin DSL: it is the default for new Gradle builds, and IDEs autocomplete and type-check it. The concepts are identical.

Dependency configurations

Maven has scopes; Gradle has configurations, buckets you add dependencies to. The java plugin defines these, and each one feeds one or more classpaths:

Configuration Compile main Run main Compile tests Run tests Leaks to consumers' compile classpath?
implementation yes yes yes yes no
api (java-library only) yes yes yes yes yes
compileOnly yes no no no no
runtimeOnly no yes no yes no
testImplementation no no yes yes no
testRuntimeOnly no no no yes no
annotationProcessor (processor path only)

Roughly, implementation is Maven's compile, compileOnly is provided, runtimeOnly is runtime, and testImplementation is test. The interesting difference is implementation vs api, which only matters when you write a library or a module other modules use:

  • A dependency in api is part of your module's public interface: your public methods take or return its types. Consumers need it to compile, so it is put on their compile classpath too.
  • A dependency in implementation is an internal detail. Consumers still get it at runtime (your code needs it), but they cannot compile against it, so they cannot accidentally depend on it, and Gradle does not need to recompile them when it changes.

This model turns the table into code. It builds the four classpaths of a module and the compile classpath of a module that depends on it:

Java Which classpath gets which dependency?

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.

Look at the last two lines. A module that depends on orders-core can compile against money (it was declared with api) but not against jackson-databind (an implementation detail), although both are on its runtime classpath. jspecify never reaches runtime, and the JUnit artifacts stay in the test classpaths. Try moving jackson-databind to api and run again: it now leaks into consumerCompile.

Default to implementation. Use api only for types that genuinely appear in your public method signatures. Smaller compile classpaths mean faster incremental builds and fewer accidental couplings, the same benefit Maven's multi-module boundaries give you.

Version conflicts, platforms and catalogs

When two versions of the same artifact meet, Gradle picks the highest requested version, unlike Maven's "nearest wins". You can override that with constraints, strict versions or a platform (Gradle's name for importing a BOM):

Kotlin
dependencies {
    implementation(platform("com.fasterxml.jackson:jackson-bom:2.22.3"))
    implementation("com.fasterxml.jackson.core:jackson-databind")      // version from the BOM
    implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

    constraints {
        implementation("org.acme:json-lite:2.4") { because("1.9 has a parsing bug") }
    }
}

In multi-module builds, put versions in one version catalog, gradle/libs.versions.toml, which Gradle reads automatically:

TOML
[versions]
jackson = "2.22.3"
junit = "6.1.3"

[libraries]
jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
junit-launcher = { module = "org.junit.platform:junit-platform-launcher" }

[plugins]
spring-boot = { id = "org.springframework.boot", version = "4.1.1" }

Build scripts then refer to type-safe accessors, and IDEs autocomplete them:

Kotlin
dependencies {
    implementation(libs.jackson.databind)
    testImplementation(libs.junit.jupiter)
    testRuntimeOnly(libs.junit.launcher)
}

Inspect what was actually resolved with ./gradlew dependencies --configuration runtimeClasspath, or ask why one artifact got its version with ./gradlew dependencyInsight --dependency jackson-core.

Tasks and the task graph

Everything Gradle does is a task: compileJava, processResources, test, jar. Tasks declare which other tasks they depend on. When you run ./gradlew build, Gradle first builds the full directed acyclic graph of every task needed, then executes it in dependency order, each task at most once. Maven's fixed phases are replaced by this graph.

The java plugin wires its tasks roughly like this. The program resolves the graph the way Gradle does: depth-first, dependencies before the task itself, each task once, and it supports -x to exclude a task.

Java Resolving Gradle's task graph

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.

jar needs only four tasks: no tests are compiled or run. build runs all eleven, each once, even though classes is needed by three different tasks. -x test removes more than one task: test was the only route to compileTestJava, processTestResources and testClasses, so they disappear too and seven tasks remain. Real Gradle behaves the same way, excluding a task together with the dependencies that nothing else needs. That is the power of a graph: Gradle computes the minimal work for what you asked.

You can add your own tasks. Register them lazily with tasks.register, which only configures a task if it is actually going to run:

Kotlin
tasks.register<Copy>("copySqlScripts") {
    group = "database"
    description = "Copies SQL migration scripts into the build folder."
    from("src/main/sql")
    into(layout.buildDirectory.dir("sql"))
}

tasks.register("printVersion") {
    val projectVersion = project.version.toString()      // read at configuration time
    doLast { println("Version: $projectVersion") }        // runs at execution time
}

tasks.named("processResources") {
    dependsOn("copySqlScripts")
}

Three build phases

Every Gradle invocation goes through three phases, and knowing them explains most confusing build-script behavior:

  1. Initialization: reads settings.gradle.kts to find which projects take part.
  2. Configuration: runs the build scripts, which configure tasks and build the graph. Code directly inside a tasks.register { } block runs here.
  3. Execution: runs the selected tasks. Only code inside doFirst { } / doLast { } and the task's actions runs here.

A classic mistake is doing real work (reading files, calling a server) at configuration time, which slows down every build, even ./gradlew tasks. Gradle's configuration cache (recommended in Gradle 9, enabled with org.gradle.configuration-cache=true in gradle.properties) skips the configuration phase entirely when nothing changed, and it reports scripts that break the rules.

Incremental builds: UP-TO-DATE

Gradle's speed comes from incremental builds. Every task declares its inputs (source files, classpath, compiler settings) and outputs (class files, a JAR). Gradle stores a fingerprint (a hash) of both. If they match the last run, the task is skipped and reported as UP-TO-DATE. With the build cache (--build-cache), outputs can even be reused from another branch, another machine or CI, reported as FROM-CACHE.

This model shows the mechanism with SHA-256 fingerprints: one build from scratch, one with nothing changed, and one after editing a single test file.

Java How UP-TO-DATE checks work

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.

The first build executes all five tasks. The second build executes none: everything is UP-TO-DATE. After editing only a test, the main code, resources and JAR stay up to date, and just compileTestJava and test run again. In a real project with hundreds of modules, this is the difference between a ten-minute build and a ten-second one. It also explains a rule: never run ./gradlew clean build out of habit. clean throws all of that away.

The Gradle wrapper

As with Maven, every Gradle project should contain the wrapper, committed to Git:

TEXT
gradlew                 (macOS/Linux script)
gradlew.bat             (Windows script)
gradle/wrapper/gradle-wrapper.jar
gradle/wrapper/gradle-wrapper.properties   (distributionUrl=...gradle-9.x-bin.zip)

./gradlew downloads the exact Gradle version the project declares, so nobody installs Gradle by hand and CI always uses the same version. Upgrade it with ./gradlew wrapper --gradle-version <new version> and commit the changed files. The first run also starts the Gradle Daemon, a background JVM that keeps build information warm between invocations; that is why the second build in a terminal is much faster than the first.

Commands you will use daily:

Terminal
./gradlew build                 # compile, test, package (assemble + check)
./gradlew test --tests "*PriceCalculatorTest"     # some tests
./gradlew :orders:test          # one module's task
./gradlew run                   # with the application plugin
./gradlew tasks                 # what can I run?
./gradlew dependencies --configuration runtimeClasspath
./gradlew build --scan          # publish a detailed build report (asks for consent first)
./gradlew test --continuous     # re-run when files change

Multi-project builds

A multi-project build lists its modules in settings.gradle.kts. Shared configuration goes into a convention plugin (a small plugin in a build-logic or buildSrc folder) rather than into allprojects { } blocks, which couple every module together and defeat the configuration cache.

Kotlin
// settings.gradle.kts
rootProject.name = "shop"
include("shop-domain", "shop-persistence", "shop-api")
Kotlin
// shop-api/build.gradle.kts
plugins {
    id("shop.java-conventions")      // our convention plugin: toolchain, test setup, lint flags
    application
}

dependencies {
    implementation(project(":shop-persistence"))
    implementation(libs.jackson.databind)
}

Maven or Gradle?

Both are excellent, both are used in serious production systems, and you should be able to read both.

Maven Gradle
Build file pom.xml, declarative XML build.gradle.kts, Kotlin code
Model Fixed lifecycle of phases Graph of tasks
Conflict resolution Nearest wins Highest version wins
Speed Good; rebuilds more than needed Incremental tasks, build cache, daemon: usually faster on big builds
Flexibility Limited by design; custom logic needs a plugin Anything is possible, which can also mean messy builds
Learning curve Gentle; every POM looks alike Steeper; builds differ more
Typical users Most Spring Boot and enterprise projects, libraries Android, large multi-module builds, Kotlin projects

A sensible rule: use what your team or framework uses. Spring Initializr offers both. If you are free to choose, Maven is the simpler default for a typical service, and Gradle pays off as the build grows large or needs custom steps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Module web depends on module core with implementation(project(":core")). core declares Jackson with implementation. Can code in web import com.fasterxml.jackson.databind.ObjectMapper?

    implementation dependencies reach consumers at runtime only. To compile against Jackson, web must declare it itself (or core must declare it with api).
  2. 2. You run ./gradlew build twice without changing anything. What does the second run report for compileJava?

    Gradle compares fingerprints of each task's inputs and outputs and skips tasks whose fingerprints are unchanged.
  3. 3. Two libraries need json-lite:1.9 and json-lite:2.4. Without any constraints, which version does Gradle select?

    Gradle's default conflict resolution picks the highest version. Maven, in contrast, picks the nearest declaration.
  4. 4. A build script contains tasks.register("report") { println("Generating") }. When is "Generating" printed?

    Code directly in the configuration block runs when the task is configured. Lazily registered tasks are configured only if needed, but work that belongs in execution must go inside doLast { }.

Summary

  • Gradle uses the same repositories, coordinates and project layout as Maven, but describes builds as Kotlin code (settings.gradle.kts, build.gradle.kts) that configures tasks.
  • Plugins (java, java-library, application, Spring Boot) add tasks and conventions; toolchains pin the JDK that compiles and tests your code.
  • Configurations replace scopes: implementation, api, compileOnly, runtimeOnly, testImplementation, testRuntimeOnly. Prefer implementation; use api only for types in your public API. With JUnit on Gradle 9, add junit-platform-launcher to testRuntimeOnly.
  • Gradle resolves conflicts to the highest version; use platforms (BOMs), constraints and a version catalog (libs.versions.toml) to stay in control.
  • A build runs in three phases (initialization, configuration, execution). Tasks form a graph; with fingerprinted inputs and outputs they become UP-TO-DATE or FROM-CACHE, which makes incremental builds fast.
  • Always commit the wrapper and use ./gradlew. Choose Maven or Gradle by what your team uses; you should be able to read both.

Next: SQL Refresher for Java Developers, the start of the JDBC chapter, where you run real SQL against an in-memory database from Java.