Gradle is a flexible build automation tool that uses a Groovy or Kotlin DSL. It combines the convention-based approach of Maven with the flexibility of scripting.

Project Structure

  my-app/
├── build.gradle.kts       # Build script (Kotlin DSL)
├── settings.gradle.kts    # Project settings
├── gradle/
│   └── wrapper/           # Gradle Wrapper
├── src/
│   ├── main/java/
│   ├── main/resources/
│   ├── test/java/
│   └── test/resources/
└── build/                 # Output (generated)
  

Minimal build.gradle.kts

  plugins {
    java
    application
}

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

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(21))
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
}

application {
    mainClass.set("com.example.Main")
}

tasks.test {
    useJUnitPlatform()
}
  

Groovy DSL Equivalent

  plugins {
    id 'java'
    id 'application'
}

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

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
}

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

test {
    useJUnitPlatform()
}
  

Common Tasks

  ./gradlew tasks              # list all tasks
./gradlew build              # compile + test + jar
./gradlew test               # run tests
./gradlew run                # run application
./gradlew clean build        # clean then build
./gradlew dependencies       # show dependency tree
./gradlew bootRun            # Spring Boot run (with plugin)
  

Gradle Wrapper

The wrapper ensures everyone uses the same Gradle version:

  gradle wrapper --gradle-version 8.5
./gradlew build   # uses wrapper, no global Gradle install needed
  

Always commit gradlew, gradlew.bat, and gradle/wrapper/ to version control.

Multi-Project Builds

settings.gradle.kts:

  rootProject.name = "my-app"
include("core", "web", "api")
  

Root build.gradle.kts:

  subprojects {
    apply(plugin = "java")
    group = "com.example"
    version = "1.0.0-SNAPSHOT"
}
  
  ./gradlew :core:build
./gradlew build   # builds all subprojects
  

Gradle vs Maven

Feature Gradle Maven
Configuration Groovy/Kotlin DSL XML POM
Flexibility High (scripting) Convention-based
Build speed Incremental, cached Phase-based
Learning curve Steeper Gentler
Spring Boot First-class support First-class support

Best Practices

  • Use Kotlin DSL (build.gradle.kts) for type safety and IDE support
  • Always use the Gradle Wrapper — do not require global Gradle install
  • Use Java Toolchain for consistent JDK version across environments
  • Prefer implementation over compile (deprecated)
  • Enable build cache: org.gradle.caching=true in gradle.properties