Gradle Builds with Groovy
Gradle is a powerful build automation tool that uses Groovy as its DSL (Domain Specific Language) for build scripts, combining the flexibility of scripting with the power of a build tool.
Why Gradle?
- Declarative builds with Groovy DSL
- Incremental builds for better performance
- Rich dependency management
- Extensible with custom tasks and plugins
- Supports multi-project builds
Basic Gradle Build Script
// build.gradle
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.apache.commons:commons-lang3:3.12.0'
testImplementation 'junit:junit:4.13.2'
}
task hello {
doLast {
println 'Hello, Gradle!'
}
}
Gradle Wrapper
The recommended way to execute Gradle builds is via the wrapper:
# Initialize wrapper
gradle wrapper --gradle-version 7.4
# Use wrapper (Windows)
gradlew.bat build
# Use wrapper (Unix/macOS)
./gradlew build
Common Gradle Tasks
Task | Description |
---|---|
clean | Deletes the build directory |
build | Assembles and tests the project |
assemble | Compiles code and builds artifacts |
test | Runs unit tests |
run | Runs the application |
Custom Tasks
task copyReports(type: Copy) {
from 'reports'
into 'archive'
include '*.pdf'
doLast {
println "Copied PDF reports to archive"
}
}
Dependency Management
dependencies {
// Module dependency
implementation 'com.google.guava:guava:31.0.1-jre'
// Project dependency
implementation project(':shared')
// File dependency
implementation files('libs/local.jar')
// Gradle version catalog (in settings.gradle)
implementation libs.guava
}
Multi-project Builds
settings.gradle:
rootProject.name = 'myapp'
include 'core', 'web', 'services'
Groovy DSL Features
- Closures for configuration blocks
- Operator overloading for dependencies
- Dynamic properties and methods
- Groovy collections and iteration
Integrating with Groovy Projects
plugins {
id 'groovy'
}
dependencies {
implementation 'org.codehaus.groovy:groovy-all:3.0.9'
testImplementation 'org.spockframework:spock-core:2.0-groovy-3.0'
}
← Back to Tutorials