Gradle Build
A Gradle build is a graph of tasks. When you type ./gradlew build, Gradle works out every task that build needs, orders them, skips the ones that are already up to date, and runs the rest.
This lesson explains the three phases of a Gradle build, how to read the task graph and task outcomes, how to write and connect your own tasks, how to configure built-in tasks, and how to split code into a multi-project build. It ends with a two-module library system that generates its own build information. If build.gradle.kts is new to you, start with Gradle in Java.
The Three Phases of a Gradle Build
Every Gradle build runs in three phases:
| Phase | What happens | Files involved |
|---|---|---|
| Initialization | Finds which projects take part | settings.gradle.kts |
| Configuration | Runs the build scripts and creates the tasks that are needed | build.gradle.kts |
| Execution | Runs the selected tasks in dependency order | Task actions (doFirst, doLast) |
Code placed directly in a build script runs during configuration. Code inside doLast runs during execution, and only if that task is selected.
// build.gradle.kts
println("Configuring project ${project.name}")
tasks.register("hello") {
println("Configuring task hello")
doLast {
println("Hello from the execution phase")
}
}
./gradlew hello
./gradlew help -q
Output:
> Configure project :
Configuring project build-demo
Configuring task hello
> Task :hello
Hello from the execution phase
BUILD SUCCESSFUL in 640ms
1 actionable task: 1 executed
Configuring project build-demo
How it works:
tasks.registercreates the task lazily. Its configuration block only runs when the task is actually needed.- The second command runs
help, sohellois never configured and its message does not appear. The top-levelprintlnstill runs, because the whole script is evaluated in every build. - Put real work in
doLast. Work done at configuration time slows down every Gradle command, even./gradlew tasks.
View the Gradle Task Graph With a Dry Run
build is a lifecycle task: it does nothing itself but depends on other tasks. A dry run (-m) prints the full list of tasks Gradle would run, without running them.
./gradlew build -m
Output for an application project:
:compileJava SKIPPED
:processResources SKIPPED
:classes SKIPPED
:jar SKIPPED
:startScripts SKIPPED
:distTar SKIPPED
:distZip SKIPPED
:assemble SKIPPED
:compileTestJava SKIPPED
:processTestResources SKIPPED
:testClasses SKIPPED
:test SKIPPED
:check SKIPPED
:build SKIPPED
BUILD SUCCESSFUL in 512ms
How it works:
- Here
SKIPPEDonly means "not run because this is a dry run". builddepends onassemble(create outputs) andcheck(verify them).checkdepends ontest, which depends on the compiled test classes, and so on.- Lifecycle tasks such as
classes,assemble,checkandbuildare convenient names for groups of real work.
Gradle Task Outcomes: UP-TO-DATE, NO-SOURCE and FROM-CACHE
With the plain console, Gradle prints the outcome of every task.
./gradlew build --console=plain
Output of a second build with no changes (shortened):
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :test UP-TO-DATE
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE
BUILD SUCCESSFUL in 798ms
| Outcome | Meaning |
|---|---|
| (no label) | The task ran |
UP-TO-DATE | Inputs and outputs unchanged since the last run, so it was skipped |
NO-SOURCE | The task had no input files, for example an empty src/main/resources |
FROM-CACHE | Outputs were copied from the build cache instead of being recomputed |
SKIPPED | The task was excluded (-x) or its onlyIf condition was false |
How it works:
- Before running a task, Gradle compares a fingerprint of its input files and settings with the previous run. If nothing changed and the outputs still exist, it skips the task.
- Edit one Java file and
compileJavaruns again;jarandtestrun again too because their inputs (the compiled classes) changed. --rerun-tasksforces every task to run, which helps when you suspect a stale result.
Create a Custom Gradle Task
Register your own task with a group, a description and an action.
tasks.register("courseInfo") {
group = "gocourse"
description = "Prints information about this project."
val projectName = project.name // read at configuration time
val javaVersion = java.toolchain.languageVersion
doLast {
println("Project: $projectName")
println("Java toolchain: ${javaVersion.get()}")
}
}
./gradlew tasks --group gocourse
./gradlew courseInfo -q
Output:
Gocourse tasks
--------------
courseInfo - Prints information about this project.
Project: grade-calculator
Java toolchain: 25
How it works:
groupanddescriptionmake the task appear in./gradlew tasksunder its own heading.- Values are read into local variables outside
doLast. Task actions should not reach back intoprojectwhile running; this keeps the task compatible with the configuration cache, which reuses the configured task graph between builds. -q(quiet) hides Gradle's own log lines, so only the task's output is shown.
Connect Gradle Tasks With dependsOn and finalizedBy
Tasks declare their order with relationships instead of running in file order.
| Method | Meaning |
|---|---|
dependsOn(x) | Run x first, always |
finalizedBy(x) | Run x afterwards, even if this task fails |
mustRunAfter(x) | If both are selected, run this one after x (does not add x) |
tasks.register("prepareData") {
doLast { println("1. Preparing data") }
}
tasks.register("cleanupTemp") {
doLast { println("3. Removing temporary files") }
}
tasks.register("report") {
dependsOn("prepareData")
finalizedBy("cleanupTemp")
doLast { println("2. Writing report") }
}
./gradlew report -q
Output:
1. Preparing data
2. Writing report
3. Removing temporary files
How it works:
- Asking for
reportpulls inprepareDatabefore it andcleanupTempafter it. - Each task runs at most once per build, even if several tasks depend on it.
finalizedBysuits cleanup work such as stopping a test server, because it runs even whenreportfails.
Use Built-In Task Types: Copy and Zip
Gradle ships typed tasks for common jobs. You configure them instead of writing actions yourself, and they get up-to-date checks for free.
tasks.register<Copy>("copyConfig") {
from("config") // config/app.properties
into(layout.buildDirectory.dir("staging/config"))
}
tasks.register<Zip>("zipSources") {
from("src/main/java")
archiveFileName = "sources.zip"
destinationDirectory = layout.buildDirectory.dir("dist")
}
./gradlew copyConfig zipSources --console=plain
./gradlew zipSources --console=plain
ls build/dist build/staging/config
Output:
> Task :copyConfig
> Task :zipSources
BUILD SUCCESSFUL in 590ms
2 actionable tasks: 2 executed
> Task :zipSources UP-TO-DATE
BUILD SUCCESSFUL in 402ms
1 actionable task: 1 up-to-date
build/dist:
sources.zip
build/staging/config:
app.properties
How it works:
tasks.register<Copy>creates a task of typeCopy.fromandintoare both its inputs and outputs, which Gradle tracks automatically.layout.buildDirectorypoints tobuild/, even if someone changes the build directory, so avoid hard-coding"build/...".- The second
zipSourcesisUP-TO-DATEbecause no source file changed.
Configure Built-In Java Tasks
Plugins create tasks such as compileJava, test and jar. You change their settings through tasks.named or the typed shortcut tasks.withType.
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
tasks.test {
useJUnitPlatform()
maxParallelForks = 2 // run test classes in 2 JVMs
}
tasks.jar {
manifest {
attributes("Implementation-Title" to project.name,
"Implementation-Version" to project.version)
}
}
./gradlew jar -q
unzip -p build/libs/grade-calculator-1.0.0.jar META-INF/MANIFEST.MF
Output:
Manifest-Version: 1.0
Implementation-Title: grade-calculator
Implementation-Version: 1.0.0
How it works:
withType<JavaCompile>()covers bothcompileJavaandcompileTestJava.configureEachapplies the settings lazily, only to tasks that are actually used.-Xlint:all -Werrormakes compiler warnings fail the build, as in Maven Plugins.- The manifest attributes end up in
META-INF/MANIFEST.MF. Lesson Build Executable JAR addsMain-Classso the JAR runs withjava -jar.
Create a Gradle Multi-Project Build
A multi-project build splits an application into subprojects that are built together. settings.gradle.kts lists them, and one subproject depends on another with project(":name").
// settings.gradle.kts
rootProject.name = "library-system"
include("core", "app")
// app/build.gradle.kts (excerpt)
dependencies {
implementation(project(":core"))
}
./gradlew projects
Output:
> Task :projects
Projects:
------------------------------------------------------------
Root project 'library-system'
------------------------------------------------------------
Root project 'library-system'
+--- Project ':app'
\--- Project ':core'
How it works:
- Each subproject is a folder with its own
build.gradle.ktsandsrc/. - Task paths include the project:
:core:testruns only core's tests, while plaintestrunstestin every project. - Gradle builds
:corebefore:appbecause of theproject(":core")dependency. Withorg.gradle.parallel=true, independent projects build at the same time.
Note: When several subprojects share the same settings (toolchain, test setup), large builds move them into a convention plugin in
buildSrcor an included build. Avoidallprojects { }blocks; they couple projects together and slow down configuration.
Real-World Example: Gradle Build for a Library System
This build has two subprojects. core holds the library logic and its tests. app is a command-line app that depends on core and prints a version number generated by a custom task during the build.
library-system/
├── settings.gradle.kts
├── gradle.properties
├── core/
│ ├── build.gradle.kts
│ └── src/main/java/com/gocourse/library/core/{Book.java, Library.java}
│ src/test/java/com/gocourse/library/core/LibraryTest.java
└── app/
├── build.gradle.kts
└── src/main/java/com/gocourse/library/app/LibraryApp.java
// settings.gradle.kts
rootProject.name = "library-system"
include("core", "app")
# gradle.properties
version=1.2.0
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
// core/build.gradle.kts
plugins {
`java-library`
}
repositories { mavenCentral() }
java {
toolchain { languageVersion = JavaLanguageVersion.of(25) }
}
dependencies {
testImplementation(platform("org.junit:junit-bom:6.1.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test { useJUnitPlatform() }
// app/build.gradle.kts
plugins {
application
}
repositories { mavenCentral() }
java {
toolchain { languageVersion = JavaLanguageVersion.of(25) }
}
dependencies {
implementation(project(":core"))
}
application {
mainClass = "com.gocourse.library.app.LibraryApp"
}
// Custom task: writes build-info.properties into a generated resources folder
val generateBuildInfo by tasks.registering {
group = "gocourse"
description = "Generates build-info.properties with the app version."
val appVersion = project.version.toString()
val outputDir = layout.buildDirectory.dir("generated/build-info")
inputs.property("version", appVersion)
outputs.dir(outputDir)
doLast {
val infoFile = outputDir.get().file("build-info.properties").asFile
infoFile.parentFile.mkdirs()
infoFile.writeText("app.version=$appVersion\n")
}
}
sourceSets.main {
resources.srcDir(generateBuildInfo) // also makes processResources depend on it
}
// core/src/main/java/com/gocourse/library/core/Book.java
package com.gocourse.library.core;
public record Book(String isbn, String title, String author) {}
// core/src/main/java/com/gocourse/library/core/Library.java
package com.gocourse.library.core;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Library {
private final Map<String, Book> booksByIsbn = new LinkedHashMap<>();
private final List<String> borrowedIsbns = new ArrayList<>();
public void add(Book book) {
booksByIsbn.put(book.isbn(), book);
}
/** Returns the borrowed book, or throws if it is unknown or already out. */
public Book borrow(String isbn) {
Book book = booksByIsbn.get(isbn);
if (book == null) {
throw new IllegalArgumentException("No book with ISBN " + isbn);
}
if (borrowedIsbns.contains(isbn)) {
throw new IllegalStateException(book.title() + " is already borrowed");
}
borrowedIsbns.add(isbn);
return book;
}
public List<Book> available() {
return booksByIsbn.values().stream()
.filter(book -> !borrowedIsbns.contains(book.isbn()))
.toList();
}
}
// core/src/test/java/com/gocourse/library/core/LibraryTest.java
package com.gocourse.library.core;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class LibraryTest {
@Test
void borrowedBookIsNoLongerAvailable() {
Library library = new Library();
library.add(new Book("111", "Java Basics", "Asha Kumar"));
library.add(new Book("222", "Gradle Guide", "Ravi Shankar"));
library.borrow("111");
assertEquals(1, library.available().size());
assertEquals("Gradle Guide", library.available().get(0).title());
}
@Test
void sameBookCannotBeBorrowedTwice() {
Library library = new Library();
library.add(new Book("111", "Java Basics", "Asha Kumar"));
library.borrow("111");
assertThrows(IllegalStateException.class, () -> library.borrow("111"));
}
}
// app/src/main/java/com/gocourse/library/app/LibraryApp.java
package com.gocourse.library.app;
import com.gocourse.library.core.Book;
import com.gocourse.library.core.Library;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LibraryApp {
public static void main(String[] args) throws IOException {
System.out.println("Library System " + appVersion());
Library library = new Library();
library.add(new Book("111", "Java Basics", "Asha Kumar"));
library.add(new Book("222", "Gradle Guide", "Ravi Shankar"));
library.add(new Book("333", "Clean Tests", "Meena Iyer"));
Book borrowed = library.borrow("222");
System.out.println("Borrowed: " + borrowed.title());
System.out.println("Available books:");
library.available().forEach(book ->
System.out.println(" - " + book.title() + " by " + book.author()));
}
private static String appVersion() throws IOException {
Properties info = new Properties();
try (InputStream in = LibraryApp.class.getResourceAsStream("/build-info.properties")) {
info.load(in);
}
return info.getProperty("app.version");
}
}
Build everything, then run the app twice:
./gradlew build
./gradlew :app:run --console=plain
./gradlew :app:run -q
Output (shortened):
BUILD SUCCESSFUL in 6s
Configuration cache entry stored.
> Task :core:compileJava UP-TO-DATE
> Task :app:generateBuildInfo UP-TO-DATE
> Task :app:processResources UP-TO-DATE
> Task :app:compileJava UP-TO-DATE
> Task :core:jar UP-TO-DATE
> Task :app:run
Library System 1.2.0
Borrowed: Gradle Guide
Available books:
- Java Basics by Asha Kumar
- Clean Tests by Meena Iyer
BUILD SUCCESSFUL in 1s
Configuration cache entry stored.
Library System 1.2.0
Borrowed: Gradle Guide
Available books:
- Java Basics by Asha Kumar
- Clean Tests by Meena Iyer
How it works:
- Initialization.
settings.gradle.ktsincludescoreandapp;gradle.propertiessetsversion=1.2.0for every project and turns on parallel builds, the build cache and the configuration cache. - Project dependency.
implementation(project(":core"))puts core's classes on the app's classpath, so:core:compileJavaalways runs (or is up to date) before:app:compileJava. - Generated resources. Passing the
generateBuildInfotask toresources.srcDirboth adds its output folder to the resources and makesprocessResourcesdepend on it. NodependsOnis needed. - Correct up-to-date checks. The task declares the version as an input and the folder as an output. Change
versioningradle.propertiesand onlygenerateBuildInfo,processResourcesand the tasks after them run again. - Configuration cache. All project values are captured before
doLast, so Gradle can store the configured build. The third command reuses that cache and skips the configuration phase entirely.
The core subproject uses the java-library plugin, which matters for how its own dependencies are shared with app. That is the topic of the next lesson, Gradle Dependencies.