Appearance
Gradle Cheatsheet
Overview
Gradle is a build automation tool that supports multi-language development. It uses a Groovy or Kotlin-based domain-specific language (DSL) instead of XML for declaring project configuration.
Installation
Package Managers
bash
# macOS
brew install gradle
# Ubuntu/Debian (via SDKMAN)
curl -s "https://get.sdkman.io" | bash
sdk install gradle
# Windows (Chocolatey)
choco install gradle
# Manual installation
wget https://services.gradle.org/distributions/gradle-8.0-bin.zip
unzip gradle-8.0-bin.zip
export PATH=$PATH:/path/to/gradle-8.0/bin
Gradle Wrapper
bash
# Generate wrapper (recommended)
gradle wrapper
# Use wrapper
./gradlew build # Unix/macOS
gradlew.bat build # Windows
Basic Project Structure
Standard Layout
project/
├── build.gradle(.kts)
├── settings.gradle(.kts)
├── gradlew
├── gradlew.bat
├── gradle/
│ └── wrapper/
├── src/
│ ├── main/
│ │ ├── java/
│ │ └── resources/
│ └── test/
│ ├── java/
│ └── resources/
└── build/
Basic build.gradle
Java Project (Groovy DSL)
groovy
plugins {
id 'java'
id 'application'
}
group = 'com.example'
version = '1.0.0'
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.apache.commons:commons-lang3:3.12.0'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:4.6.1'
}
application {
mainClass = 'com.example.Main'
}
test {
useJUnitPlatform()
}
Java Project (Kotlin DSL)
kotlin
plugins {
java
application
}
group = "com.example"
version = "1.0.0"
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.apache.commons:commons-lang3:3.12.0")
testImplementation("junit:junit:4.13.2")
testImplementation("org.mockito:mockito-core:4.6.1")
}
application {
mainClass.set("com.example.Main")
}
tasks.test {
useJUnitPlatform()
}
Tasks
Built-in Tasks
bash
# Build tasks
./gradlew build # Full build
./gradlew assemble # Build without tests
./gradlew clean # Clean build directory
./gradlew check # Run all checks
# Java tasks
./gradlew compileJava # Compile main Java sources
./gradlew compileTestJava # Compile test sources
./gradlew test # Run tests
./gradlew jar # Create JAR file
# Application tasks
./gradlew run # Run application
./gradlew installDist # Create distribution
./gradlew distZip # Create ZIP distribution
# Help tasks
./gradlew tasks # List available tasks
./gradlew help # Show help
./gradlew properties # Show project properties
Custom Tasks (Groovy)
groovy
task hello {
doLast {
println 'Hello, World!'
}
}
task copyFiles(type: Copy) {
from 'src/main/resources'
into 'build/resources'
}
task createDocs(type: Javadoc) {
source = sourceSets.main.allJava
classpath = configurations.compileClasspath
}
// Task with dependencies
task buildAll {
dependsOn 'clean', 'build', 'createDocs'
}
// Task with configuration
task processTemplates(type: Copy) {
from 'src/templates'
into 'build/generated'
expand(project.properties)
}
Custom Tasks (Kotlin)
kotlin
tasks.register("hello") {
doLast {
println("Hello, World!")
}
}
tasks.register<Copy>("copyFiles") {
from("src/main/resources")
into("build/resources")
}
tasks.register<Javadoc>("createDocs") {
source = sourceSets.main.get().allJava
classpath = configurations.compileClasspath.get()
}
// Task with dependencies
tasks.register("buildAll") {
dependsOn("clean", "build", "createDocs")
}
Dependencies
Dependency Configurations
groovy
dependencies {
// Compile time and runtime
implementation 'org.springframework:spring-core:5.3.21'
// Compile time only
compileOnly 'org.projectlombok:lombok:1.18.24'
// Runtime only
runtimeOnly 'mysql:mysql-connector-java:8.0.29'
// Test dependencies
testImplementation 'junit:junit:4.13.2'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
// Annotation processor
annotationProcessor 'org.projectlombok:lombok:1.18.24'
// API (for library projects)
api 'org.apache.commons:commons-lang3:3.12.0'
}
Version Management
groovy
// Version catalog (gradle/libs.versions.toml)
[versions]
spring = "5.3.21"
junit = "4.13.2"
[libraries]
spring-core = { module = "org.springframework:spring-core", version.ref = "spring" }
junit = { module = "junit:junit", version.ref = "junit" }
// In build.gradle
dependencies {
implementation libs.spring.core
testImplementation libs.junit
}
// Version constraints
dependencies {
implementation('org.springframework:spring-core') {
version {
strictly '[5.0, 6.0['
prefer '5.3.21'
}
}
}
Dependency Resolution
groovy
configurations.all {
resolutionStrategy {
// Force specific version
force 'org.slf4j:slf4j-api:1.7.36'
// Fail on version conflict
failOnVersionConflict()
// Cache for 24 hours
cacheDynamicVersionsFor 24, 'hours'
cacheChangingModulesFor 24, 'hours'
}
}
// Exclude transitive dependencies
dependencies {
implementation('org.springframework:spring-core') {
exclude group: 'commons-logging', module: 'commons-logging'
}
}
Multi-Project Builds
settings.gradle
groovy
rootProject.name = 'my-multi-project'
include 'core'
include 'web'
include 'api'
// Custom project locations
include 'shared'
project(':shared').projectDir = file('shared-library')
Root build.gradle
groovy
allprojects {
group = 'com.example'
version = '1.0.0'
repositories {
mavenCentral()
}
}
subprojects {
apply plugin: 'java'
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
dependencies {
testImplementation 'junit:junit:4.13.2'
}
}
// Configure specific projects
project(':web') {
apply plugin: 'war'
dependencies {
implementation project(':core')
implementation 'org.springframework:spring-webmvc:5.3.21'
}
}
Project Dependencies
groovy
// In web/build.gradle
dependencies {
implementation project(':core')
implementation project(':api')
// Specific configuration
testImplementation project(path: ':core', configuration: 'testFixtures')
}
Plugins
Applying Plugins
groovy
// Core plugins
plugins {
id 'java'
id 'application'
id 'maven-publish'
}
// Community plugins
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'com.github.johnrengelman.shadow' version '7.1.2'
}
// Legacy plugin application
apply plugin: 'java'
apply from: 'gradle/dependencies.gradle'
Popular Plugins
groovy
// Spring Boot
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}
// Shadow JAR (fat JAR)
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.2'
}
shadowJar {
archiveBaseName = 'my-app'
archiveClassifier = ''
archiveVersion = ''
}
// Docker
plugins {
id 'com.bmuschko.docker-java-application' version '7.4.0'
}
docker {
javaApplication {
baseImage = 'openjdk:11-jre-slim'
maintainer = 'Your Name <your.email@example.com>'
ports = [8080]
images = ['my-app:latest']
}
}
Testing
JUnit 5
groovy
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
exceptionFormat "full"
}
// System properties
systemProperty 'junit.jupiter.execution.parallel.enabled', 'true'
// JVM arguments
jvmArgs '-Xmx1024m'
}
// Custom test task
task integrationTest(type: Test) {
useJUnitPlatform()
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
Test Reports
groovy
test {
reports {
html.enabled = true
xml.enabled = true
junitXml.enabled = true
}
finalizedBy jacocoTestReport
}
// Jacoco code coverage
plugins {
id 'jacoco'
}
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
}
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.8
}
}
}
}
Build Configuration
Source Sets
groovy
sourceSets {
main {
java {
srcDirs = ['src/main/java', 'src/generated/java']
}
resources {
srcDirs = ['src/main/resources', 'src/main/config']
}
}
integrationTest {
java {
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
}
}
}
configurations {
integrationTestImplementation.extendsFrom testImplementation
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
}
Build Types
groovy
// Environment-specific builds
if (project.hasProperty('env')) {
apply from: "gradle/env-${project.env}.gradle"
}
// Debug/Release configurations
task debugJar(type: Jar) {
archiveClassifier = 'debug'
from sourceSets.main.output
}
task releaseJar(type: Jar) {
archiveClassifier = 'release'
from sourceSets.main.output
// Minimize JAR
exclude '**/debug/**'
exclude '**/*Test.class'
}
Publishing
Maven Publishing
groovy
plugins {
id 'maven-publish'
id 'signing'
}
publishing {
publications {
maven(MavenPublication) {
from components.java
pom {
name = 'My Library'
description = 'A concise description of my library'
url = 'http://www.example.com/library'
licenses {
license {
name = 'The Apache License, Version 2.0'
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id = 'johndoe'
name = 'John Doe'
email = 'john.doe@example.com'
}
}
scm {
connection = 'scm:git:git://example.com/my-library.git'
developerConnection = 'scm:git:ssh://example.com/my-library.git'
url = 'http://example.com/my-library/'
}
}
}
}
repositories {
maven {
name = "OSSRH"
url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
credentials {
username = ossrhUsername
password = ossrhPassword
}
}
}
}
signing {
sign publishing.publications.maven
}
Command Line Usage
Basic Commands
bash
# Build project
./gradlew build
# Clean build
./gradlew clean build
# Run tests
./gradlew test
# Run application
./gradlew run
# Create distribution
./gradlew installDist
# Publish to repository
./gradlew publish
Advanced Options
bash
# Parallel execution
./gradlew build --parallel
# Offline mode
./gradlew build --offline
# Refresh dependencies
./gradlew build --refresh-dependencies
# Profile build
./gradlew build --profile
# Debug mode
./gradlew build --debug
# Continuous build
./gradlew build --continuous
# Build specific project
./gradlew :web:build
# Exclude tasks
./gradlew build -x test
System Properties
bash
# Set system properties
./gradlew build -Dorg.gradle.debug=true
# Set project properties
./gradlew build -Penv=production
# Set JVM options
./gradlew build -Dorg.gradle.jvmargs="-Xmx2g -XX:+HeapDumpOnOutOfMemoryError"
Gradle Properties
gradle.properties
properties
# JVM settings
org.gradle.jvmargs=-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError
# Gradle daemon
org.gradle.daemon=true
# Parallel execution
org.gradle.parallel=true
# Build cache
org.gradle.caching=true
# Configuration cache
org.gradle.configuration-cache=true
# Project properties
version=1.0.0
group=com.example
# Custom properties
database.url=jdbc:mysql://localhost:3306/mydb
api.key=your-api-key
Environment-Specific Properties
bash
# gradle-dev.properties
database.url=jdbc:h2:mem:testdb
debug.enabled=true
# gradle-prod.properties
database.url=jdbc:mysql://prod-server:3306/mydb
debug.enabled=false
# Usage
./gradlew build -Penv=dev
Performance Optimization
Build Cache
groovy
// Enable build cache
buildCache {
local {
enabled = true
directory = file("${rootDir}/.gradle/build-cache")
}
remote(HttpBuildCache) {
url = 'https://example.com/build-cache/'
push = true
credentials {
username = buildCacheUsername
password = buildCachePassword
}
}
}
Parallel Execution
properties
# gradle.properties
org.gradle.parallel=true
org.gradle.workers.max=4
org.gradle.configureondemand=true
Incremental Compilation
groovy
tasks.withType(JavaCompile) {
options.incremental = true
options.fork = true
options.forkOptions.jvmArgs = ['-Xmx1024m']
}
Best Practices
Project Structure
groovy
// Use version catalog
dependencyResolutionManagement {
versionCatalogs {
libs {
from(files("gradle/libs.versions.toml"))
}
}
}
// Consistent formatting
plugins {
id 'com.diffplug.spotless' version '6.7.2'
}
spotless {
java {
googleJavaFormat()
removeUnusedImports()
trimTrailingWhitespace()
endWithNewline()
}
}
Error Handling
groovy
// Fail fast on dependency conflicts
configurations.all {
resolutionStrategy.failOnVersionConflict()
}
// Validate required properties
if (!project.hasProperty('apiKey')) {
throw new GradleException('apiKey property is required')
}
// Check Java version
if (!JavaVersion.current().isJava11Compatible()) {
throw new GradleException('Java 11 or higher is required')
}
Troubleshooting
Common Issues
bash
# Clear Gradle cache
rm -rf ~/.gradle/caches/
# Refresh dependencies
./gradlew build --refresh-dependencies
# Debug dependency resolution
./gradlew dependencies
./gradlew dependencyInsight --dependency spring-core
# Check for deprecated features
./gradlew build --warning-mode all
# Profile build performance
./gradlew build --profile --scan
Debug Mode
bash
# Enable debug logging
./gradlew build --debug
# Enable info logging
./gradlew build --info
# Stack trace on failure
./gradlew build --stacktrace
Resources
- Official Documentation: gradle.org/docs
- User Guide: docs.gradle.org/current/userguide
- Plugin Portal: plugins.gradle.org
- Build Scans: gradle.com