Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Build Tools and Ecosystem

Gradle Build Scripts with Groovy

Understand build.gradle, the Gradle Groovy DSL: plugins, dependencies, tasks, configuration versus execution, custom tasks, properties and multi-project builds.

The most common place you meet Groovy is not a Groovy application at all: it is build.gradle. Gradle, the build tool behind Android and a large share of Java and Kotlin projects, accepts build scripts written in Groovy (build.gradle) or Kotlin (build.gradle.kts). A Groovy build script is a DSL built exactly the way you learned in Closure Delegates and DSLs: blocks are closures, and each block configures an object (the "delegate").

Gradle cannot run on this site, so build files are shown read-only. The Java stand-ins model how a build graph runs tasks in dependency order.

A typical build.gradle

GROOVY
plugins {
  id 'java'
  id 'application'
  id 'groovy'
}

group = 'com.example'
version = '1.0.0'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.apache.groovy:groovy:4.0.22'
  implementation 'com.google.guava:guava:33.2.1-jre'
  testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0'
  testRuntimeOnly 'net.bytebuddy:byte-buddy:1.14.17'
}

application {
  mainClass = 'com.example.Main'
}

tasks.named('test') {
  useJUnitPlatform()
}

Read it as Groovy:

  • plugins { id 'java' } calls the method plugins with a closure, and id 'java' is id('java') inside it.
  • group = '...' sets a property on the project object.
  • dependencies { implementation 'x:y:1' } is a method call named after the configuration; the string is a Maven coordinate group:artifact:version.
  • tasks.named('test') { ... } configures an existing task.

The version numbers above are examples; check Maven Central for current ones.

Dependency configurations

Configuration Meaning
implementation Needed to compile and run; hidden from consumers' compile classpath
api Same, but exposed to consumers (needs the java-library plugin)
compileOnly Only to compile (annotations, provided APIs)
runtimeOnly Only at runtime (JDBC drivers)
testImplementation For test code
annotationProcessor Compile-time processors

Dynamic notation in Groovy lets you write maps too: implementation group: 'com.google.guava', name: 'guava', version: '33.2.1-jre'.

Tasks

A task is a unit of work. Plugins add tasks (build, test, jar, run), and you can write your own:

GROOVY
tasks.register('hello') {
  group = 'demo'
  description = 'Prints a greeting'
  doLast {
    println "Hello from ${project.name} ${version}"
  }
}

tasks.register('package-docs', Zip) {
  from 'docs'
  archiveFileName = 'docs.zip'
  destinationDirectory = layout.buildDirectory.dir('dist')
}

tasks.register('release') {
  dependsOn 'test', 'package-docs'
  doLast { println 'released' }
}

Run with gradle hello or the wrapper ./gradlew hello (use the wrapper in every project so everyone uses the same Gradle version). gradle tasks lists tasks, gradle build --dry-run shows what would run.

Configuration phase and execution phase

Gradle runs a build in phases, and mixing them up is the most common beginner mistake:

  1. Initialization: which projects take part (settings.gradle).
  2. Configuration: all build scripts run top to bottom, and tasks are created and configured. Code outside doLast/doFirst runs here, for every build, even if the task is never executed.
  3. Execution: only the selected tasks (and dependencies) run their actions.
GROOVY
tasks.register('slow') {
  println "configuring"              // runs on every Gradle invocation
  doLast {
    println "executing"              // runs only when 'slow' is requested
  }
}

Put heavy work such as reading files or calling a server inside doLast, or use lazy providers.

Properties and variables

GROOVY
ext {                         // extra project properties (old style)
  junitVersion = '5.10.2'
}
def appName = 'demo'          // a local script variable

gradle.properties holds values like org.gradle.jvmargs=-Xmx2g and your own myFlag=true, read in the script with project.findProperty('myFlag'). Command line: gradle build -PmyFlag=false. Secrets should come from environment variables (System.getenv('TOKEN')) and never be committed.

Multi-project builds

settings.gradle lists the modules:

GROOVY
rootProject.name = 'shop'
include 'core', 'web', 'cli'

Then a module depends on a sibling with implementation project(':core'). Shared rules go in the root build.gradle inside subprojects { } or, better, in a convention plugin kept in buildSrc or an included build.

Groovy DSL versus Kotlin DSL

The Groovy DSL is shorter and more dynamic. The Kotlin DSL (build.gradle.kts) offers IDE completion and compile-time checks. Both are fully supported, and the examples on the Gradle site are shown in both. For learning Groovy, the Groovy DSL is the better exercise, because you will recognize the delegate pattern everywhere.

Try it: a task graph runner (stand-in)

Gradle executes each task after the tasks it depends on, exactly once. This Java program does a depth-first run of such a graph.

Java Stand-in: tasks and dependsOn

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.

Try it: configuration versus execution (stand-in)

Code outside the action runs while the build is being set up. Code inside runs only if the task is requested.

Java Stand-in: two phases of a build

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What kind of Groovy construct is the dependencies { ... } block?

    Gradle build scripts are Groovy: each block is a closure whose delegate is the object being configured.
  2. 2. When does code directly inside tasks.register('x') { ... } (outside doLast) run?

    The registration closure configures the task during configuration. Actions belong in doLast.
  3. 3. Which dependency configuration is for libraries needed only when the program runs, such as a JDBC driver?

    runtimeOnly dependencies are on the runtime classpath but not the compile classpath.
  4. 4. Why use the Gradle wrapper (./gradlew)?

    The wrapper downloads and runs the Gradle version declared in the project, so builds are reproducible.

Summary

  • build.gradle is a Groovy DSL: blocks are closures configuring Gradle objects.
  • plugins, repositories, dependencies and tasks are the core blocks.
  • Tasks have actions (doLast) and dependencies (dependsOn); the build has configuration and execution phases.
  • Use gradle.properties, -P and environment variables for settings; the wrapper for the version.
  • Multi-project builds use settings.gradle and project(':x') dependencies.

Next: Grape and Dependency Management in Scripts