Java Academy Logo

Gradle Build Script Structure

A Gradle build script tells Gradle how to build, test, and run your project. It is written in Groovy (build.gradle) or Kotlin (build.gradle.kts).

Main Parts of a Gradle Build Script

1. Plugins

Plugins add features to your project.

  • java → for Java projects
  • application → for runnable apps
build.gradle
plugins {
    id 'java'
    id 'application'
}

2. Repositories

Repositories tell Gradle where to download libraries from. Most projects use Maven Central.

build.gradle
repositories {
    mavenCentral()
}

3. Dependencies

Dependencies are libraries your project needs.

  • implementation → used while running the app
  • testImplementation → used only for testing
build.gradle
dependencies {
    implementation 'org.springframework:spring-core:5.3.8'
    testImplementation 'junit:junit:4.13.2'
}

4. Tasks

Tasks are actions Gradle performs (build, test, clean, etc.). You can also create custom tasks.

build.gradle
task hello {
    doLast {
        println 'Hello, Gradle'
    }
}

5. Project Properties

Used to set project details like version.

build.gradle
project.version = '1.0.0'

6. Source Sets

Tell Gradle where your code is located. (Default is src/main/java)

build.gradle
sourceSets {
    main {
        java {
            srcDirs = ['src/main/java']
        }
    }
}

7. Task Order (Dependencies)

You can control which task runs first.

build.gradle
task clean {
    delete 'build'
}

task compileJava {
    dependsOn clean
}

8. Default Tasks

Runs a task automatically when no task is specified.

build.gradle
defaultTasks 'build'

Simple Full Example

Here's a complete Gradle build script combining all the main parts:

build.gradle
plugins {
    id 'java'
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework:spring-core:5.3.8'
    testImplementation 'junit:junit:4.13.2'
}

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

task hello {
    doLast {
        println 'Hello, Gradle'
    }
}