Saltar a contenido

Gradle Cheatsheet

Overview

Gradle is a build automation tool that suppuertos multi-language development. It uses a Groovy or Kotlin-based domain-specific language (DSL) instead of XML for declaring project configuración.

instalación

Package Managers

# macOS
brew install gradle

# Ubuntu/Debian (via SDKMAN)
curl -s "https://get.sdkman.io"|bash
sdk install gradle

# Windows (Chocolatey)
choco install gradle

# Manual instalación
wget https://servicios.gradle.org/distributions/gradle-8.0-bin.zip
unzip gradle-8.0-bin.zip
expuerto PATH=$PATH:/path/to/gradle-8.0/bin

Gradle Wrapper

# 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)

plugins \\\\{
    id 'java'
    id 'application'
\\\\}

group = 'com.ejemplo'
version = '1.0.0'

java \\\\{
    sourceCompatibility = JavaVersion.VERSION_11
    objetivoCompatibility = 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.ejemplo.Main'
\\\\}

test \\\\{
    useJUnitPlatform()
\\\\}

Java Project (Kotlin DSL)

plugins \\\\{
    java
    application
\\\\}

group = "com.ejemplo"
version = "1.0.0"

java \\\\{
    sourceCompatibility = JavaVersion.VERSION_11
    objetivoCompatibility = 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.ejemplo.Main")
\\\\}

tasks.test \\\\{
    useJUnitPlatform()
\\\\}

Tasks

Built-in Tasks

# 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)

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 = configuracións.compileClasspath
\\\\}

// Task with dependencies
task buildAll \\\\{
    dependsOn 'clean', 'build', 'createDocs'
\\\\}

// Task with configuración
task procesoTemplates(type: Copy) \\\\{
    from 'src/templates'
    into 'build/generated'
    expand(project.properties)
\\\\}

Custom Tasks (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 = configuracións.compileClasspath.get()
\\\\}

// Task with dependencies
tasks.register("buildAll") \\\\{
    dependsOn("clean", "build", "createDocs")
\\\\}

Dependencies

Dependency configuracións

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 procesoor
    annotationprocesoor 'org.projectlombok:lombok:1.18.24'

    // API (for library projects)
    api 'org.apache.commons:commons-lang3:3.12.0'
\\\\}

Version Management

// 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

configuracións.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

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

allprojects \\\\{
    group = 'com.ejemplo'
    version = '1.0.0'

    repositories \\\\{
        mavenCentral()
    \\\\}
\\\\}

subprojects \\\\{
    apply plugin: 'java'

    java \\\\{
        sourceCompatibility = JavaVersion.VERSION_11
        objetivoCompatibility = 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

// In web/build.gradle
dependencies \\\\{
    implementation project(':core')
    implementation project(':api')

    // Specific configuración
    testImplementation project(path: ':core', configuración: 'testFixtures')
\\\\}

Plugins

Applying Plugins

// 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'
// 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@ejemplo.com>``'
        puertos = [8080]
        images = ['my-app:latest']
    \\\\}
\\\\}

Testing

JUnit 5

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 Repuertos

test \\\\{
    repuertos \\\\{
        html.enabled = true
        xml.enabled = true
        junitXml.enabled = true
    \\\\}

    finalizedBy jacocoTestRepuerto
\\\\}

// Jacoco code coverage
plugins \\\\{
    id 'jacoco'
\\\\}

jacocoTestRepuerto \\\\{
    repuertos \\\\{
        xml.enabled true
        html.enabled true
    \\\\}
\\\\}

jacocoTestCoverageVerification \\\\{
    violationRules \\\\{
        rule \\\\{
            limit \\\\{
                minimum = 0.8
            \\\\}
        \\\\}
    \\\\}
\\\\}

Build configuración

Source Sets

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
        \\\\}
    \\\\}
\\\\}

configuracións \\\\{
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
\\\\}

Build Types

// Environment-specific builds
if (project.hasProperty('env')) \\\\{
    apply from: "gradle/env-$\\\\{project.env\\\\}.gradle"
\\\\}

// Debug/Release configuracións
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

plugins \\\\{
    id 'maven-publish'
    id 'signing'
\\\\}

publishing \\\\{
    publications \\\\{
        maven(MavenPublication) \\\\{
            from components.java

            pom \\\\{
                name = 'My Library'
                Descripción = 'A concise Descripción of my library'
                url = 'http://www.ejemplo.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@ejemplo.com'
                    \\\\}
                \\\\}

                scm \\\\{
                    conexión = 'scm:git:git://ejemplo.com/my-library.git'
                    developerconexión = 'scm:git:ssh://ejemplo.com/my-library.git'
                    url = 'http://ejemplo.com/my-library/'
                \\\\}
            \\\\}
        \\\\}
    \\\\}

    repositories \\\\{
        maven \\\\{
            name = "OSSRH"
            url = "https://oss.sonatype.org/servicio/local/staging/deploy/maven2/"
            credenciales \\\\{
                nombre de usuario = ossrhnombre de usuario
                contraseña = ossrhcontraseña
            \\\\}
        \\\\}
    \\\\}
\\\\}

signing \\\\{
    sign publishing.publications.maven
\\\\}

comando Line uso

Basic comandos

# 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 opcións

# 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

# Set system properties
./gradlew build -Dorg.gradle.debug=true

# Set project properties
./gradlew build -Penv=production

# Set JVM opcións
./gradlew build -Dorg.gradle.jvmargs="-Xmx2g -XX:+HeapDumpOnOutOfMemoryError"

Gradle Properties

gradle.properties

# JVM settings
org.gradle.jvmargs=-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError

# Gradle demonio
org.gradle.demonio=true

# Parallel execution
org.gradle.parallel=true

# Build cache
org.gradle.caching=true

# configuración cache
org.gradle.configuración-cache=true

# Project properties
version=1.0.0
group=com.ejemplo

# Custom properties
database.url=jdbc:mysql://localhost:3306/mydb
api.clave=your-api-clave

Environment-Specific Properties

# 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

# uso
./gradlew build -Penv=dev

Performance Optimization

Build Cache

// Enable build cache
buildCache \\\\{
    local \\\\{
        enabled = true
        directory = file("$\\\\{rootDir\\\\}/.gradle/build-cache")
    \\\\}

    remote(HttpBuildCache) \\\\{
        url = 'https://ejemplo.com/build-cache/'
        push = true
        credenciales \\\\{
            nombre de usuario = buildCachenombre de usuario
            contraseña = buildCachecontraseña
        \\\\}
    \\\\}
\\\\}

Parallel Execution

# gradle.properties
org.gradle.parallel=true
org.gradle.workers.max=4
org.gradle.configureondemand=true

Incremental Compilation

tasks.withType(JavaCompile) \\\\{
    opcións.incremental = true
    opcións.fork = true
    opcións.forkopcións.jvmArgs = ['-Xmx1024m']
\\\\}

Best Practices

Project Structure

// 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()
        removeUnusedImpuertos()
        trimTrailingWhitespace()
        endWithNewline()
    \\\\}
\\\\}

Error Handling

// Fail fast on dependency conflicts
configuracións.all \\\\{
    resolutionStrategy.failOnVersionConflict()
\\\\}

// Validate required properties
if (!project.hasProperty('apiclave')) \\\\{
    throw new GradleException('apiclave property is required')
\\\\}

// Check Java version
if (!JavaVersion.current().isJava11Compatible()) \\\\{
    throw new GradleException('Java 11 or higher is required')
\\\\}

solución de problemas

Common Issues

# 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

# Enable debug logging
./gradlew build --debug

# Enable info logging
./gradlew build --info

# Stack trace on failure
./gradlew build --stacktrace

Resources