Gradle 全网最细学习手册(下篇)

0 阅读17分钟

🚀 Gradle 全网最细学习手册(下篇)

💡 企业级实战:掌握多项目构建、自定义插件开发、性能优化,通过完整实战案例成为Gradle专家!

📖 学习导航

  • 🎯 适合人群:已掌握Gradle基础概念,想深入学习高级应用的开发者
  • ⏱️ 学习时长:建议4-6天完成下篇内容
  • 🎓 学习目标:掌握企业级Gradle应用、多项目管理、插件开发和性能优化
  • 📚 学习方式:理论+实战,通过完整项目案例掌握高级技能

📚 系列文章导航

  • 📖 上篇:基础概念 + DSL语法 + 任务系统 + 依赖管理
  • 📖 下篇:多项目构建 + 插件开发 + 性能优化 + 实战案例

📌 第四阶段:多项目构建与高级特性

🏗️ 8. 多项目构建管理

多项目构建是Gradle的核心优势之一,能够高效管理复杂的企业级项目结构。

8.1 多项目结构设计

📁 典型多项目结构

my-multi-project/
├── settings.gradle                 # 项目设置
├── build.gradle                   # 根项目构建脚本
├── gradle.properties              # 全局属性
├── gradle/
│   └── wrapper/
├── buildSrc/                      # 构建逻辑模块
│   ├── build.gradle
│   └── src/main/groovy/
├── common/                        # 公共模块
│   ├── build.gradle
│   └── src/
├── api/                          # API模块
│   ├── build.gradle
│   └── src/
├── service/                      # 服务模块
│   ├── build.gradle
│   └── src/
├── web/                          # Web模块
│   ├── build.gradle
│   └── src/
└── integration-tests/            # 集成测试模块
    ├── build.gradle
    └── src/
8.2 根项目配置

⚙️ settings.gradle 详细配置

// ==================== 项目基本信息 ====================
// 根项目名称:影响生成的JAR文件名
rootProject.name = 'my-multi-project'

// ==================== 子项目包含配置 ====================
// 标准子项目包含
include 'common'
include 'api'
include 'service'
include 'web'
include 'integration-tests'

// 嵌套项目包含
include 'common:common-core'
include 'common:common-web'
include 'common:common-data'

// 服务模块
include 'services:user-service'
include 'services:order-service'
include 'services:payment-service'

// 基础设施模块
include 'infrastructure:config-server'
include 'infrastructure:eureka-server'

// ==================== 项目目录映射 ====================
// 自定义项目目录结构
project(':common').projectDir = file('modules/common')
project(':api').projectDir = file('modules/api')

// 批量设置服务模块目录
['user-service', 'order-service', 'payment-service'].each { serviceName ->
    project(":services:${serviceName}").projectDir = file("services/${serviceName}")
}

// ==================== 插件管理详解 ====================
pluginManagement {
    // 插件仓库配置
    repositories {
        gradlePluginPortal()    // Gradle官方插件门户
        mavenCentral()          // Maven中央仓库
        // 企业私有插件仓库
        maven {
            url = 'https://nexus.company.com/repository/gradle-plugins/'
            credentials {
                username = providers.gradleProperty('nexusUsername').orNull
                password = providers.gradleProperty('nexusPassword').orNull
            }
        }
    }

    // 插件版本管理:统一管理所有插件版本
    plugins {
        // Spring Boot相关
        id 'org.springframework.boot' version '2.7.0'
        id 'io.spring.dependency-management' version '1.0.11.RELEASE'

        // 代码质量
        id 'jacoco' version '0.8.8'
        id 'com.github.spotbugs' version '5.0.9'
        id 'checkstyle' version '10.3.1'

        // 容器化
        id 'com.palantir.docker' version '0.34.0'
        id 'com.google.cloud.tools.jib' version '3.2.1'

        // 文档生成
        id 'org.asciidoctor.jvm.convert' version '3.3.2'

        // 性能分析
        id 'com.gradle.build-scan' version '3.11'
    }

    // 插件解析策略
    resolutionStrategy {
        eachPlugin {
            // 自定义插件解析逻辑
            if (requested.id.namespace == 'com.company') {
                useModule('com.company:gradle-plugins:1.0.0')
            }
        }
    }
}

// ==================== 依赖解析管理详解 ====================
dependencyResolutionManagement {
    // 仓库模式:FAIL_ON_PROJECT_REPOS 确保所有仓库在这里统一配置
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

    // 统一仓库配置
    repositories {
        // 本地仓库(开发环境)
        if (providers.gradleProperty('useLocalRepo').isPresent()) {
            mavenLocal()
        }

        // 企业私有仓库
        maven {
            name = 'CompanyNexus'
            url = 'https://nexus.company.com/repository/maven-public/'
            credentials {
                username = providers.gradleProperty('nexusUsername').orNull
                password = providers.gradleProperty('nexusPassword').orNull
            }
        }

        // 国内镜像(加速下载)
        maven {
            name = 'Aliyun'
            url = 'https://maven.aliyun.com/repository/public'
        }

        // Maven中央仓库
        mavenCentral()

        // Spring仓库
        maven {
            name = 'SpringRepo'
            url = 'https://repo.spring.io/milestone'
            mavenContent {
                includeGroupByRegex 'org\\.springframework.*'
            }
        }
    }

    // 版本目录配置(Gradle 7.0+)
    versionCatalogs {
        libs {
            // 定义版本
            version('spring-boot', '2.7.0')
            version('spring-cloud', '2021.0.3')
            version('junit', '5.9.2')

            // 定义库
            library('spring-boot-starter-web', 'org.springframework.boot', 'spring-boot-starter-web').versionRef('spring-boot')
            library('spring-boot-starter-test', 'org.springframework.boot', 'spring-boot-starter-test').versionRef('spring-boot')
            library('junit-jupiter', 'org.junit.jupiter', 'junit-jupiter').versionRef('junit')

            // 定义插件
            plugin('spring-boot', 'org.springframework.boot').versionRef('spring-boot')
            plugin('spring-dependency-management', 'io.spring.dependency-management').version('1.0.11.RELEASE')

            // 定义bundle(依赖组合)
            bundle('spring-boot-web', ['spring-boot-starter-web', 'spring-boot-starter-actuator'])
            bundle('testing', ['junit-jupiter', 'spring-boot-starter-test'])
        }
    }
}

// ==================== 构建缓存配置 ====================
buildCache {
    local {
        enabled = true
        directory = file('build-cache')
        removeUnusedEntriesAfterDays = 30
    }

    remote(HttpBuildCache) {
        url = 'https://cache.company.com/'
        push = providers.gradleProperty('pushToCache').isPresent()
        credentials {
            username = providers.gradleProperty('cacheUsername').orNull
            password = providers.gradleProperty('cachePassword').orNull
        }
    }
}

// ==================== 特性预览配置 ====================
enableFeaturePreview('TYPESAFE_PROJECT_ACCESSORS')
enableFeaturePreview('VERSION_CATALOGS')

💡 settings.gradle配置实战案例

案例1:大型企业项目配置

// 企业级多模块项目settings.gradle
rootProject.name = 'enterprise-platform'

// 核心模块
include 'platform-core'
include 'platform-common'
include 'platform-security'

// 业务模块
['user', 'order', 'payment', 'inventory'].each { module ->
    include "business-${module}"
    project(":business-${module}").projectDir = file("business/${module}")
}

// 基础设施模块
['gateway', 'config', 'registry', 'monitor'].each { infra ->
    include "infra-${infra}"
    project(":infra-${infra}").projectDir = file("infrastructure/${infra}")
}

pluginManagement {
    repositories {
        // 企业私有插件仓库优先
        maven {
            url = 'https://nexus.corp.com/repository/gradle-plugins/'
            credentials {
                username = System.getenv('CORP_NEXUS_USER')
                password = System.getenv('CORP_NEXUS_PASS')
            }
        }
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        // 企业仓库优先
        maven {
            url = 'https://nexus.corp.com/repository/maven-public/'
            credentials {
                username = System.getenv('CORP_NEXUS_USER')
                password = System.getenv('CORP_NEXUS_PASS')
            }
        }
        mavenCentral()
    }
}

案例2:开源项目配置

// 开源项目settings.gradle
rootProject.name = 'awesome-library'

include 'core'
include 'extensions'
include 'examples'
include 'benchmarks'

pluginManagement {
    repositories {
        gradlePluginPortal()
        mavenCentral()
    }

    plugins {
        id 'java-library'
        id 'maven-publish'
        id 'signing'
        id 'org.gradle.test-retry' version '1.4.1'
        id 'com.gradle.plugin-publish' version '1.0.0'
    }
}

dependencyResolutionManagement {
    repositories {
        mavenCentral()
        // 快照版本仓库
        maven {
            url = 'https://oss.sonatype.org/content/repositories/snapshots/'
            mavenContent {
                snapshotsOnly()
            }
        }
    }
}

📋 根项目 build.gradle

// 应用于所有项目的配置
allprojects {
    group = 'com.example'
    version = '1.0.0-SNAPSHOT'
    
    repositories {
        mavenCentral()
    }
}

// 应用于所有子项目的配置
subprojects {
    apply plugin: 'java'
    apply plugin: 'java-library'
    
    java {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    
    // 公共依赖
    dependencies {
        implementation 'org.slf4j:slf4j-api:1.7.36'
        testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
        testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
    }
    
    // 公共任务配置
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs += ['-parameters']
    }
    
    test {
        useJUnitPlatform()
        testLogging {
            events 'passed', 'skipped', 'failed'
        }
    }
}

// 特定项目配置
project(':web') {
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
    
    dependencies {
        implementation project(':service')
        implementation 'org.springframework.boot:spring-boot-starter-web'
    }
}

project(':service') {
    dependencies {
        implementation project(':api')
        implementation project(':common')
        implementation 'org.springframework.boot:spring-boot-starter'
    }
}

project(':api') {
    dependencies {
        api project(':common')
        api 'javax.validation:validation-api:2.0.1.Final'
    }
}

// 聚合任务
task buildAll {
    dependsOn subprojects.collect { it.tasks.named('build') }
    description = '构建所有子项目'
    group = 'build'
}

task testAll {
    dependsOn subprojects.collect { it.tasks.named('test') }
    description = '测试所有子项目'
    group = 'verification'
}
8.3 子项目配置示例

📦 common模块 (common/build.gradle)

// 公共工具模块
dependencies {
    api 'org.apache.commons:commons-lang3:3.12.0'
    api 'com.fasterxml.jackson.core:jackson-databind:2.13.3'
    api 'com.google.guava:guava:31.1-jre'
    
    implementation 'org.slf4j:slf4j-api:1.7.36'
    
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
    testImplementation 'org.assertj:assertj-core:3.23.1'
}

// 生成源码jar
java {
    withSourcesJar()
    withJavadocJar()
}

🔧 service模块 (service/build.gradle)

plugins {
    id 'org.springframework.boot'
    id 'io.spring.dependency-management'
}

dependencies {
    // 项目依赖
    implementation project(':api')
    implementation project(':common')
    
    // Spring Boot依赖
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    
    // 数据库
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation 'com.h2database:h2'
    
    // 测试
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

// 禁用bootJar任务(这是一个库,不是应用)
jar {
    enabled = true
    archiveClassifier = ''
}

bootJar {
    enabled = false
}

🌐 web模块 (web/build.gradle)

plugins {
    id 'org.springframework.boot'
    id 'io.spring.dependency-management'
}

dependencies {
    // 项目依赖
    implementation project(':service')
    
    // Spring Boot Web
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    
    // 前端资源处理
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    
    // 测试
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.boot:spring-boot-testcontainers'
    testImplementation 'org.testcontainers:mysql'
}

// Spring Boot配置
springBoot {
    buildInfo()
    mainClass = 'com.example.web.WebApplication'
}

// 构建Docker镜像
task buildImage {
    dependsOn bootBuildImage
    description = '构建Docker镜像'
    group = 'build'
}
8.4 多项目构建命令
# 构建所有项目
./gradlew build

# 构建特定项目
./gradlew :web:build
./gradlew :service:test

# 运行特定项目
./gradlew :web:bootRun

# 查看项目结构
./gradlew projects

# 查看特定项目的任务
./gradlew :web:tasks

# 并行构建
./gradlew build --parallel

# 构建依赖的项目
./gradlew :web:build --include-build

# 持续构建
./gradlew build --continuous

🔌 9. 自定义插件开发

9.1 插件开发方式

📝 脚本插件(简单场景)

// gradle/common.gradle
// 可复用的构建逻辑

ext {
    springBootVersion = '2.7.0'
    junitVersion = '5.9.2'
}

configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
}

sourceSets {
    integrationTest {
        java.srcDir 'src/integration-test/java'
        resources.srcDir 'src/integration-test/resources'
    }
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
    
    useJUnitPlatform()
    
    testLogging {
        events 'passed', 'skipped', 'failed'
    }
}

// 在项目中使用
// apply from: rootProject.file('gradle/common.gradle')

🏗️ buildSrc插件(项目级插件)

// buildSrc/build.gradle
plugins {
    id 'groovy-gradle-plugin'
}

repositories {
    gradlePluginPortal()
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-gradle-plugin:2.7.0'
}
// buildSrc/src/main/groovy/com.example.java-conventions.gradle
// 约定插件

plugins {
    id 'java'
    id 'jacoco'
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
    withSourcesJar()
    withJavadocJar()
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
    options.compilerArgs += ['-parameters', '-Xlint:unchecked']
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required = true
        html.required = true
    }
}

🎯 独立插件项目

// my-gradle-plugin/build.gradle
plugins {
    id 'java-gradle-plugin'
    id 'groovy'
    id 'maven-publish'
}

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

repositories {
    gradlePluginPortal()
    mavenCentral()
}

dependencies {
    implementation gradleApi()
    implementation localGroovy()
    
    testImplementation 'org.spockframework:spock-core:2.3-groovy-3.0'
}

gradlePlugin {
    plugins {
        myPlugin {
            id = 'com.example.my-plugin'
            implementationClass = 'com.example.MyPlugin'
            displayName = 'My Custom Plugin'
            description = 'A custom Gradle plugin'
        }
    }
}

// 发布配置
publishing {
    repositories {
        maven {
            url = 'https://nexus.company.com/repository/gradle-plugins/'
            credentials {
                username = project.findProperty('nexusUsername')
                password = project.findProperty('nexusPassword')
            }
        }
    }
}
9.2 插件实现示例

🎯 自定义任务类

// src/main/groovy/com/example/tasks/GreetingTask.groovy
package com.example.tasks

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.*

class GreetingTask extends DefaultTask {

    @Input
    String greeting = 'Hello'

    @Input
    String recipient = 'World'

    @OutputFile
    File outputFile

    @TaskAction
    void greet() {
        def message = "${greeting}, ${recipient}!"
        println message

        if (outputFile) {
            outputFile.parentFile.mkdirs()
            outputFile.text = message
        }
    }
}

🔌 插件主类

// src/main/groovy/com/example/MyPlugin.groovy
package com.example

import com.example.tasks.GreetingTask
import org.gradle.api.Plugin
import org.gradle.api.Project

class MyPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        // 创建扩展
        def extension = project.extensions.create('myPlugin', MyPluginExtension)

        // 注册任务
        project.tasks.register('greeting', GreetingTask) { task ->
            task.greeting = extension.greeting
            task.recipient = extension.recipient
            task.outputFile = project.file("${project.buildDir}/greeting.txt")
        }

        // 配置现有任务
        project.tasks.named('build') {
            dependsOn 'greeting'
        }

        // 添加配置
        project.afterEvaluate {
            println "MyPlugin applied to ${project.name}"
        }
    }
}

// 扩展类
class MyPluginExtension {
    String greeting = 'Hello'
    String recipient = 'Gradle'
}

📝 使用自定义插件

// build.gradle
plugins {
    id 'com.example.my-plugin' version '1.0.0'
}

myPlugin {
    greeting = 'Hi'
    recipient = 'Developer'
}

⚡ 10. 性能优化与最佳实践

10.1 构建性能优化

🚀 Gradle Daemon优化详解

# gradle.properties

# ==================== Daemon基础配置 ====================
# 启用Gradle Daemon(强烈推荐)
org.gradle.daemon=true
# 作用:避免JVM启动开销,显著提升构建速度
# 效果:首次构建后,后续构建速度提升50-80%

# Daemon超时时间(毫秒)
org.gradle.daemon.idletimeout=3600000
# 说明:Daemon空闲1小时后自动停止
# 建议:开发环境设置较长时间,CI环境可设置较短

# ==================== JVM参数优化 ====================
# 基础JVM参数
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# 详细参数说明:
# -Xmx4g                           # 最大堆内存4GB
# -XX:MaxMetaspaceSize=512m        # 元空间最大512MB
# -XX:+HeapDumpOnOutOfMemoryError  # OOM时生成堆转储文件
# -Dfile.encoding=UTF-8            # 文件编码UTF-8

# 高性能JVM参数(推荐用于大型项目)
# org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC -XX:+UseStringDeduplication -XX:+OptimizeStringConcat

# ==================== 内存配置策略 ====================
# 小型项目(<10个模块)
# org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=256m

# 中型项目(10-50个模块)
# org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m

# 大型项目(>50个模块)
# org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC

# 超大型项目(>100个模块)
# org.gradle.jvmargs=-Xmx16g -XX:MaxMetaspaceSize=2g -XX:+UseG1GC -XX:+UseStringDeduplication

💡 Daemon优化实战案例

案例1:开发环境优化配置

# ~/.gradle/gradle.properties (开发环境)
# 开发环境:最大化性能
org.gradle.daemon=true
org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC
org.gradle.daemon.idletimeout=7200000  # 2小时超时

# 开发环境特定优化
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.caching=true
org.gradle.vfs.watch=true              # 文件系统监控(Gradle 6.5+)

案例2:CI/CD环境配置

# gradle.properties (CI环境)
# CI环境:稳定性优先
org.gradle.daemon=false               # CI环境不使用daemon
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m
org.gradle.parallel=true              # 启用并行构建
org.gradle.caching=true               # 启用构建缓存

# CI环境特定配置
org.gradle.console=plain              # 纯文本输出
org.gradle.logging.level=info         # 详细日志
org.gradle.warning.mode=fail          # 警告时失败

案例3:容器环境配置

# gradle.properties (Docker容器)
# 容器环境:资源受限优化
org.gradle.daemon=false               # 容器中不使用daemon
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=256m -XX:+UseSerialGC
org.gradle.parallel=false             # 容器中禁用并行(避免资源竞争)
org.gradle.workers.max=2              # 限制工作线程数

🔄 并行构建优化

# gradle.properties
# 启用并行构建
org.gradle.parallel=true

# 配置并行工作线程数
org.gradle.workers.max=4

# 按需配置
org.gradle.configureondemand=true

💾 构建缓存优化详解

# gradle.properties

# ==================== 构建缓存基础配置 ====================
# 启用构建缓存(核心性能优化)
org.gradle.caching=true
# 效果:可以将构建时间减少50-90%
# 原理:缓存任务输出,避免重复执行相同任务

# 启用HTTP构建缓存调试
org.gradle.caching.debug=true
# 作用:显示缓存命中/未命中信息
# 用途:调试缓存配置,优化缓存策略

# ==================== 配置缓存(实验性功能) ====================
# 启用配置缓存(Gradle 6.6+)
org.gradle.unsafe.configuration-cache=true
# 作用:缓存项目配置,加速后续构建
# 注意:实验性功能,可能与某些插件不兼容

# 配置缓存问题处理
org.gradle.unsafe.configuration-cache-problems=warn
# 可选值:warn, fail
# 建议:开发阶段使用warn,CI环境使用fail
// build.gradle - 构建缓存详细配置
buildCache {
    // ==================== 本地缓存配置 ====================
    local {
        enabled = true
        // 缓存目录:默认在 ~/.gradle/caches/build-cache-1
        directory = file('build-cache')

        // 清理策略:30天后删除未使用的缓存条目
        removeUnusedEntriesAfterDays = 30

        // 缓存大小限制(可选)
        // targetSizeInMB = 5000  // 限制为5GB
    }

    // ==================== 远程缓存配置 ====================
    remote(HttpBuildCache) {
        // 远程缓存服务器URL
        url = 'https://cache.company.com/'

        // 推送权限:只有CI环境推送缓存
        push = project.hasProperty('ci') || System.getenv('CI') != null

        // 认证信息
        credentials {
            username = project.findProperty('cacheUsername') ?: System.getenv('CACHE_USERNAME')
            password = project.findProperty('cachePassword') ?: System.getenv('CACHE_PASSWORD')
        }

        // 连接配置
        allowUntrustedServer = false
        allowInsecureProtocol = false

        // 超时配置
        // connectionTimeoutMs = 30000
        // socketTimeoutMs = 30000
    }
}

// ==================== 任务缓存配置 ====================
// 为自定义任务启用缓存
tasks.register('processFiles', ProcessFilesTask) {
    // 输入文件
    inputFiles.from(fileTree('src/main/resources'))

    // 输出目录
    outputDir = file('build/processed')

    // 启用缓存
    outputs.cacheIf { true }

    // 缓存键配置
    inputs.property('version', project.version)
    inputs.property('environment', project.findProperty('env') ?: 'dev')
}

// 禁用特定任务的缓存
tasks.named('someTask') {
    outputs.doNotCacheIf('Task has side effects') { true }
}

// ==================== 缓存策略配置 ====================
// 全局缓存策略
tasks.withType(JavaCompile).configureEach {
    // 启用增量编译
    options.incremental = true

    // 缓存配置
    outputs.cacheIf { true }
}

tasks.withType(Test).configureEach {
    // 测试任务缓存配置
    outputs.cacheIf {
        // 只有在没有系统属性变化时才缓存
        !project.hasProperty('rerunTests')
    }
}

💡 构建缓存实战案例

案例1:企业级缓存配置

// settings.gradle - 企业级缓存配置
buildCache {
    local {
        enabled = true
        directory = file('/opt/gradle-cache')  // 使用SSD路径
        removeUnusedEntriesAfterDays = 7       // 企业环境快速清理
    }

    remote(HttpBuildCache) {
        url = 'https://gradle-cache.company.com/'

        // 只有CI环境和发布分支推送缓存
        push = (System.getenv('CI') != null) &&
               (System.getenv('BRANCH_NAME') in ['main', 'develop'])

        credentials {
            username = System.getenv('GRADLE_CACHE_USER')
            password = System.getenv('GRADLE_CACHE_PASS')
        }

        // 企业网络配置
        allowUntrustedServer = false
        connectionTimeoutMs = 10000
        socketTimeoutMs = 30000
    }
}

案例2:开源项目缓存配置

// build.gradle - 开源项目缓存配置
buildCache {
    local {
        enabled = true
        removeUnusedEntriesAfterDays = 14
    }

    // 使用Gradle Build Cache Node
    remote(HttpBuildCache) {
        url = 'https://ge.gradle.org/cache/'
        push = false  // 开源项目通常只读取缓存
    }
}

// 针对开源项目的缓存优化
tasks.withType(Javadoc).configureEach {
    // JavaDoc生成通常很慢,启用缓存
    outputs.cacheIf { true }
}

tasks.withType(Test).configureEach {
    // 测试缓存配置
    outputs.cacheIf {
        // 只有在测试代码和依赖没有变化时才缓存
        !project.hasProperty('forceTests')
    }
}

案例3:多环境缓存策略

// build.gradle - 多环境缓存策略
buildCache {
    local {
        enabled = true
        directory = file("${System.getProperty('user.home')}/.gradle/build-cache")

        // 根据环境调整清理策略
        removeUnusedEntriesAfterDays = project.hasProperty('dev') ? 7 : 30
    }

    remote(HttpBuildCache) {
        def cacheUrl = project.findProperty('cacheUrl') ?:
                      System.getenv('GRADLE_CACHE_URL')

        if (cacheUrl) {
            url = cacheUrl

            // 环境特定的推送策略
            push = project.hasProperty('pushCache') ||
                   System.getenv('GRADLE_CACHE_PUSH') == 'true'

            credentials {
                username = project.findProperty('cacheUser') ?:
                          System.getenv('GRADLE_CACHE_USER')
                password = project.findProperty('cachePass') ?:
                          System.getenv('GRADLE_CACHE_PASS')
            }
        }
    }
}

🎯 11. 环境配置管理实战

11.1 多环境配置策略

📝 gradle.properties 环境配置

# ==================== 基础配置 ====================
# 项目基本信息
version=1.0.0-SNAPSHOT
group=com.example

# ==================== 环境特定配置 ====================
# 开发环境配置(默认)
spring.profiles.active=dev
database.url=jdbc:mysql://localhost:3306/myapp_dev
database.username=dev_user
database.password=dev_password
redis.host=localhost
redis.port=6379
log.level=DEBUG

# 可以通过命令行覆盖:
# ./gradlew build -Pspring.profiles.active=prod

🔧 build.gradle 环境配置处理

// ==================== 环境配置处理 ====================
// 环境检测
def environment = project.findProperty('env') ?: 'dev'
def isProduction = environment == 'prod'
def isDevelopment = environment == 'dev'
def isTesting = environment == 'test'

// 根据环境设置属性
ext {
    env = environment

    // 数据库配置
    dbUrl = project.findProperty('database.url') ?: 'jdbc:h2:mem:testdb'
    dbUsername = project.findProperty('database.username') ?: 'sa'
    dbPassword = project.findProperty('database.password') ?: ''

    // Redis配置
    redisHost = project.findProperty('redis.host') ?: 'localhost'
    redisPort = project.findProperty('redis.port') ?: '6379'

    // 日志配置
    logLevel = project.findProperty('log.level') ?: 'INFO'

    // Spring配置
    springProfiles = project.findProperty('spring.profiles.active') ?: 'dev'
}

// ==================== 环境特定依赖 ====================
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

    // 开发环境依赖
    if (isDevelopment) {
        developmentOnly 'org.springframework.boot:spring-boot-devtools'
        runtimeOnly 'com.h2database:h2'
    }

    // 生产环境依赖
    if (isProduction) {
        runtimeOnly 'mysql:mysql-connector-java'
        implementation 'io.micrometer:micrometer-registry-prometheus'
    }

    // 测试环境依赖
    if (isTesting) {
        testImplementation 'org.testcontainers:mysql'
        testImplementation 'org.testcontainers:redis'
    }
}

// ==================== 环境特定任务配置 ====================
tasks.named('bootRun') {
    systemProperty 'spring.profiles.active', springProfiles
    systemProperty 'database.url', dbUrl
    systemProperty 'database.username', dbUsername
    systemProperty 'database.password', dbPassword
    systemProperty 'redis.host', redisHost
    systemProperty 'redis.port', redisPort

    // 开发环境特定配置
    if (isDevelopment) {
        systemProperty 'spring.devtools.restart.enabled', 'true'
        systemProperty 'logging.level.com.example', 'DEBUG'
    }
}

tasks.named('test') {
    systemProperty 'spring.profiles.active', 'test'
    systemProperty 'database.url', 'jdbc:h2:mem:testdb'

    // 测试环境JVM参数
    jvmArgs = ['-Xmx1024m', '-XX:MaxMetaspaceSize=256m']
}

// ==================== 资源文件处理 ====================
tasks.named('processResources') {
    // 资源文件属性替换
    filesMatching(['**/*.properties', '**/*.yml']) {
        expand(
            version: project.version,
            environment: environment,
            databaseUrl: dbUrl,
            databaseUsername: dbUsername,
            redisHost: redisHost,
            redisPort: redisPort,
            logLevel: logLevel
        )
    }
}
11.2 配置文件管理策略

📁 配置文件结构

src/main/resources/
├── application.yml                 # 基础配置
├── application-dev.yml            # 开发环境配置
├── application-test.yml           # 测试环境配置
├── application-prod.yml           # 生产环境配置
├── config/
│   ├── database-dev.properties   # 开发数据库配置
│   ├── database-test.properties  # 测试数据库配置
│   └── database-prod.properties  # 生产数据库配置
└── templates/
    ├── application.yml.template   # 配置模板
    └── logback-spring.xml.template

📝 application.yml 模板

# application.yml
server:
  port: 8080
  servlet:
    context-path: /api

spring:
  profiles:
    active: ${environment}

  application:
    name: ${project.name}
    version: ${version}

  datasource:
    url: ${databaseUrl}
    username: ${databaseUsername}
    password: ${databasePassword}
    driver-class-name: com.mysql.cj.jdbc.Driver

  redis:
    host: ${redisHost}
    port: ${redisPort}
    database: 0

logging:
  level:
    com.example: ${logLevel}
    org.springframework: INFO
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
    file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%X{traceId}] %logger{50} - %msg%n"

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      show-details: when-authorized
11.3 环境配置实战案例

案例1:多环境构建脚本

// build.gradle - 多环境构建配置
// 环境配置映射
def environmentConfigs = [
    dev: [
        profile: 'dev',
        dbUrl: 'jdbc:mysql://localhost:3306/myapp_dev',
        dbUser: 'dev_user',
        dbPass: 'dev_password',
        redisHost: 'localhost',
        logLevel: 'DEBUG',
        skipTests: false
    ],
    test: [
        profile: 'test',
        dbUrl: 'jdbc:mysql://test-server:3306/myapp_test',
        dbUser: 'test_user',
        dbPass: System.getenv('TEST_DB_PASSWORD'),
        redisHost: 'test-redis.company.com',
        logLevel: 'INFO',
        skipTests: false
    ],
    prod: [
        profile: 'prod',
        dbUrl: 'jdbc:mysql://prod-cluster:3306/myapp_prod',
        dbUser: 'prod_user',
        dbPass: System.getenv('PROD_DB_PASSWORD'),
        redisHost: 'prod-redis-cluster.company.com',
        logLevel: 'WARN',
        skipTests: true
    ]
]

// 获取当前环境配置
def currentEnv = project.findProperty('env') ?: 'dev'
def config = environmentConfigs[currentEnv]

if (!config) {
    throw new GradleException("Unknown environment: ${currentEnv}")
}

// 应用环境配置
ext {
    environmentConfig = config
}

// 环境特定任务
task deployToEnvironment {
    group = 'deployment'
    description = "Deploy to ${currentEnv} environment"

    doLast {
        println "Deploying to ${currentEnv} environment..."
        println "Database: ${config.dbUrl}"
        println "Redis: ${config.redisHost}"
        println "Log Level: ${config.logLevel}"

        // 执行部署逻辑
        if (config.skipTests) {
            println "Skipping tests for ${currentEnv} environment"
        } else {
            println "Running tests for ${currentEnv} environment"
        }
    }
}

// 环境验证任务
task validateEnvironment {
    group = 'verification'
    description = "Validate ${currentEnv} environment configuration"

    doLast {
        println "Validating ${currentEnv} environment..."

        // 验证必需的环境变量
        def requiredEnvVars = []
        if (currentEnv == 'test') {
            requiredEnvVars = ['TEST_DB_PASSWORD']
        } else if (currentEnv == 'prod') {
            requiredEnvVars = ['PROD_DB_PASSWORD', 'PROD_REDIS_PASSWORD']
        }

        requiredEnvVars.each { envVar ->
            if (!System.getenv(envVar)) {
                throw new GradleException("Required environment variable not set: ${envVar}")
            }
        }

        println "Environment validation passed for ${currentEnv}"
    }
}

// 构建前验证环境
tasks.named('build') {
    dependsOn validateEnvironment
}

案例2:Docker多环境构建

// build.gradle - Docker多环境构建
apply plugin: 'com.palantir.docker'

docker {
    name = "${project.name}:${project.version}-${currentEnv}"

    // 基础镜像
    dockerfile file('docker/Dockerfile')

    // 构建参数
    buildArgs([
        'JAR_FILE': "build/libs/${project.name}-${project.version}.jar",
        'ENVIRONMENT': currentEnv,
        'JAVA_OPTS': getJavaOpts(currentEnv)
    ])

    // 文件复制
    files tasks.bootJar.outputs.files
    files 'docker/entrypoint.sh'
    files "src/main/resources/application-${currentEnv}.yml"
}

// 根据环境获取JVM参数
def getJavaOpts(env) {
    def javaOpts = [
        dev: '-Xmx1g -Xms512m -XX:+UseG1GC',
        test: '-Xmx2g -Xms1g -XX:+UseG1GC',
        prod: '-Xmx4g -Xms2g -XX:+UseG1GC -XX:+UseStringDeduplication'
    ]
    return javaOpts[env] ?: javaOpts['dev']
}

// 环境特定Docker任务
task buildDockerDev {
    group = 'docker'
    description = 'Build Docker image for development'
    dependsOn 'bootJar'
    finalizedBy 'docker'

    doFirst {
        project.ext.currentEnv = 'dev'
    }
}

task buildDockerProd {
    group = 'docker'
    description = 'Build Docker image for production'
    dependsOn 'bootJar'
    finalizedBy 'docker'

    doFirst {
        project.ext.currentEnv = 'prod'
    }
}

📊 增量构建优化

// 正确配置任务输入输出
task processFiles {
    inputs.files fileTree('src/main/resources')
    inputs.property 'version', project.version
    outputs.dir 'build/processed'

    // 启用缓存
    outputs.cacheIf { true }

    doLast {
        // 处理逻辑
    }
}

// 使用注解方式
class ProcessTask extends DefaultTask {
    @InputFiles
    @PathSensitive(PathSensitivity.RELATIVE)
    FileCollection inputFiles

    @Input
    String version

    @OutputDirectory
    File outputDir

    @TaskAction
    void process() {
        // 处理逻辑
    }
}
10.2 依赖解析优化

🔍 依赖解析策略

configurations.all {
    resolutionStrategy {
        // 缓存动态版本
        cacheDynamicVersionsFor 10, 'minutes'
        cacheChangingModulesFor 4, 'hours'

        // 组件选择规则
        componentSelection {
            all { ComponentSelection selection ->
                if (selection.candidate.version.contains('alpha')) {
                    selection.reject('Alpha versions not allowed')
                }
            }
        }

        // 依赖替换
        dependencySubstitution {
            substitute module('commons-logging:commons-logging') with module('org.slf4j:jcl-over-slf4j:1.7.36')
        }
    }
}

📦 仓库优化

repositories {
    // 使用本地仓库
    mavenLocal()

    // 使用国内镜像
    maven {
        name = 'Aliyun'
        url = 'https://maven.aliyun.com/repository/public'
    }

    // 限制仓库内容
    maven {
        url = 'https://repo.spring.io/milestone'
        mavenContent {
            includeGroupByRegex 'org\\.springframework.*'
        }
    }

    // 最后使用中央仓库
    mavenCentral()
}
10.3 构建脚本优化

🎯 避免配置时间过长

// ❌ 避免在配置阶段执行耗时操作
task badTask {
    // 这会在配置阶段执行
    def result = expensiveOperation()

    doLast {
        println result
    }
}

// ✅ 推荐做法
task goodTask {
    doLast {
        // 在执行阶段才执行
        def result = expensiveOperation()
        println result
    }
}

// ✅ 使用Provider API
def expensiveProvider = providers.provider {
    expensiveOperation()
}

task betterTask {
    doLast {
        println expensiveProvider.get()
    }
}

🔧 任务配置优化

// ✅ 使用任务配置避免
tasks.configureEach { task ->
    if (task instanceof Test) {
        task.useJUnitPlatform()
        task.testLogging {
            events 'passed', 'skipped', 'failed'
        }
    }
}

// ✅ 延迟配置
tasks.withType(JavaCompile).configureEach {
    options.encoding = 'UTF-8'
    options.compilerArgs.addAll(['-parameters', '-Xlint:unchecked'])
}

📌 第五阶段:实战案例与企业级应用

🎯 11. 实战案例:Spring Boot微服务项目

11.1 项目结构设计
microservice-project/
├── settings.gradle
├── build.gradle
├── gradle.properties
├── buildSrc/
│   ├── build.gradle
│   └── src/main/groovy/
├── common/
│   ├── common-core/
│   ├── common-web/
│   └── common-data/
├── services/
│   ├── user-service/
│   ├── order-service/
│   └── payment-service/
├── gateway/
│   └── api-gateway/
├── infrastructure/
│   ├── config-server/
│   ├── eureka-server/
│   └── monitoring/
└── docker/
    ├── docker-compose.yml
    └── Dockerfile.template
11.2 根项目配置

⚙️ settings.gradle

rootProject.name = 'microservice-project'

// 公共模块
include 'common:common-core'
include 'common:common-web'
include 'common:common-data'

// 业务服务
include 'services:user-service'
include 'services:order-service'
include 'services:payment-service'

// 基础设施
include 'gateway:api-gateway'
include 'infrastructure:config-server'
include 'infrastructure:eureka-server'
include 'infrastructure:monitoring'

pluginManagement {
    plugins {
        id 'org.springframework.boot' version '2.7.0'
        id 'io.spring.dependency-management' version '1.0.11.RELEASE'
        id 'com.palantir.docker' version '0.34.0'
        id 'com.google.cloud.tools.jib' version '3.2.1'
    }
}

📋 根项目 build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.7.0' apply false
    id 'io.spring.dependency-management' version '1.0.11.RELEASE' apply false
}

ext {
    springBootVersion = '2.7.0'
    springCloudVersion = '2021.0.3'
    testcontainersVersion = '1.17.3'
}

allprojects {
    group = 'com.example.microservice'
    version = '1.0.0-SNAPSHOT'

    repositories {
        maven { url 'https://maven.aliyun.com/repository/public' }
        mavenCentral()
    }
}

subprojects {
    apply plugin: 'java'
    apply plugin: 'io.spring.dependency-management'

    java {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }

    dependencyManagement {
        imports {
            mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}"
            mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
            mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}"
        }
    }

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter'
        implementation 'org.springframework.boot:spring-boot-starter-actuator'

        testImplementation 'org.springframework.boot:spring-boot-starter-test'
        testImplementation 'org.testcontainers:junit-jupiter'
    }

    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs += ['-parameters']
    }

    test {
        useJUnitPlatform()
        testLogging {
            events 'passed', 'skipped', 'failed'
        }
    }
}

// 服务项目配置
configure(subprojects.findAll { it.path.startsWith(':services:') }) {
    apply plugin: 'org.springframework.boot'

    dependencies {
        implementation project(':common:common-core')
        implementation project(':common:common-web')
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    }
}

// 公共模块配置
configure(subprojects.findAll { it.path.startsWith(':common:') }) {
    jar {
        enabled = true
        archiveClassifier = ''
    }

    bootJar {
        enabled = false
    }
}
11.3 服务模块配置示例

🔧 user-service/build.gradle

plugins {
    id 'org.springframework.boot'
    id 'com.google.cloud.tools.jib'
}

dependencies {
    // 项目依赖
    implementation project(':common:common-core')
    implementation project(':common:common-web')
    implementation project(':common:common-data')

    // Spring Boot
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // Spring Cloud
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.cloud:spring-cloud-starter-sleuth'

    // 数据库
    runtimeOnly 'mysql:mysql-connector-java'

    // 测试
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
    testImplementation 'org.testcontainers:mysql'
}

springBoot {
    buildInfo()
    mainClass = 'com.example.microservice.user.UserServiceApplication'
}

// Docker镜像构建
jib {
    from {
        image = 'openjdk:11-jre-slim'
    }
    to {
        image = "microservice/${project.name}:${project.version}"
        tags = ['latest']
    }
    container {
        jvmFlags = ['-Xmx512m', '-Dfile.encoding=UTF-8']
        ports = ['8080']
        environment = [
            'SPRING_PROFILES_ACTIVE': 'docker'
        ]
    }
}

// 集成测试配置
configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
}

sourceSets {
    integrationTest {
        java.srcDir 'src/integration-test/java'
        resources.srcDir 'src/integration-test/resources'
    }
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath

    useJUnitPlatform()

    shouldRunAfter test

    testLogging {
        events 'passed', 'skipped', 'failed'
    }
}

check.dependsOn integrationTest
11.4 构建脚本优化

🎯 buildSrc/src/main/groovy/microservice-conventions.gradle

// 微服务约定插件
plugins {
    id 'java'
    id 'org.springframework.boot'
    id 'io.spring.dependency-management'
    id 'jacoco'
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
    withSourcesJar()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'

    // 监控和追踪
    implementation 'org.springframework.cloud:spring-cloud-starter-sleuth'
    implementation 'io.micrometer:micrometer-registry-prometheus'

    // 测试
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.testcontainers:junit-jupiter'
}

// 测试配置
test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport

    testLogging {
        events 'passed', 'skipped', 'failed'
        exceptionFormat = 'full'
    }
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required = true
        html.required = true
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: [
                '**/config/**',
                '**/dto/**',
                '**/entity/**',
                '**/*Application.*'
            ])
        }))
    }
}

// 健康检查任务
task healthCheck {
    group = 'verification'
    description = '执行服务健康检查'

    doLast {
        def port = project.findProperty('server.port') ?: '8080'
        def url = "http://localhost:${port}/actuator/health"

        try {
            def response = new URL(url).text
            println "Health check passed: ${response}"
        } catch (Exception e) {
            throw new GradleException("Health check failed: ${e.message}")
        }
    }
}

⚡ 12. 常用命令与工具

12.1 基础构建命令
# 基础命令
./gradlew build              # 完整构建
./gradlew clean              # 清理构建产物
./gradlew assemble           # 组装(不运行测试)
./gradlew check              # 检查(包括测试)
./gradlew test               # 运行测试
./gradlew jar                # 创建JAR文件

# 多项目命令
./gradlew :user-service:build           # 构建特定项目
./gradlew :user-service:bootRun         # 运行Spring Boot应用
./gradlew build --parallel              # 并行构建
./gradlew build --continue              # 失败后继续构建其他项目

# 依赖相关
./gradlew dependencies                  # 查看依赖树
./gradlew dependencyInsight --dependency spring-core
./gradlew buildEnvironment              # 查看构建环境
./gradlew properties                    # 查看项目属性
12.2 性能分析命令
# 构建性能分析
./gradlew build --profile               # 生成性能报告
./gradlew build --scan                  # 构建扫描(需要Gradle Enterprise)
./gradlew build --dry-run               # 干运行,查看任务执行顺序

# 调试命令
./gradlew build --debug                 # 调试模式
./gradlew build --info                  # 详细信息
./gradlew build --stacktrace            # 显示堆栈跟踪
./gradlew build --full-stacktrace       # 显示完整堆栈跟踪

# 缓存相关
./gradlew build --build-cache           # 启用构建缓存
./gradlew cleanBuildCache               # 清理构建缓存
12.3 任务管理命令
# 任务查看
./gradlew tasks                         # 查看所有任务
./gradlew tasks --all                   # 查看所有任务(包括依赖任务)
./gradlew :user-service:tasks           # 查看特定项目任务

# 任务执行
./gradlew myTask                        # 执行自定义任务
./gradlew myTask --rerun-tasks          # 强制重新执行任务
./gradlew myTask --offline              # 离线模式执行

# 任务依赖
./gradlew myTask --dry-run              # 查看任务执行计划
./gradlew help --task myTask            # 查看任务帮助信息

🔧 13. 故障排除与调试

13.1 常见问题解决

❌ 问题1:构建缓存问题

# 症状:构建结果不一致,任务被错误跳过
# 解决方案:
./gradlew clean build --no-build-cache
./gradlew cleanBuildCache

# 检查任务输入输出配置
./gradlew myTask --info

❌ 问题2:依赖解析失败

# 症状:Could not resolve dependency
# 解决方案:
./gradlew dependencies --refresh-dependencies
./gradlew build --refresh-dependencies

# 检查仓库配置
./gradlew buildEnvironment

❌ 问题3:内存不足

# 症状:OutOfMemoryError
# 解决方案:调整gradle.properties
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g

# 或者临时设置
export GRADLE_OPTS="-Xmx4g"
./gradlew build

❌ 问题4:Daemon问题

# 症状:构建卡住或异常
# 解决方案:
./gradlew --stop                        # 停止所有daemon
./gradlew --no-daemon build             # 不使用daemon构建
./gradlew --status                      # 查看daemon状态
13.2 调试技巧

🔍 构建脚本调试

// 添加调试输出
println "Current project: ${project.name}"
println "Java version: ${java.sourceCompatibility}"

// 任务执行前后钩子
gradle.taskGraph.whenReady { taskGraph ->
    println "Tasks to execute: ${taskGraph.allTasks*.name}"
}

gradle.taskGraph.afterTask { task, taskState ->
    if (taskState.failure) {
        println "Task ${task.name} failed: ${taskState.failure}"
    }
}

// 项目评估钩子
gradle.projectsEvaluated {
    println "All projects evaluated"
}

📊 性能分析

// 任务执行时间统计
class TimingPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.gradle.addListener(new TaskExecutionTimeListener())
    }
}

class TaskExecutionTimeListener implements TaskExecutionListener {
    private long startTime

    void beforeExecute(Task task) {
        startTime = System.currentTimeMillis()
    }

    void afterExecute(Task task, TaskState state) {
        long duration = System.currentTimeMillis() - startTime
        println "${task.path} took ${duration}ms"
    }
}

🏆 14. 最佳实践总结

14.1 项目结构最佳实践
# ✅ 推荐的多项目结构
my-gradle-project/
├── settings.gradle                     # 项目设置
├── build.gradle                       # 根构建脚本
├── gradle.properties                  # 项目属性
├── buildSrc/                          # 构建逻辑
│   ├── build.gradle
│   └── src/main/groovy/
├── gradle/
│   └── wrapper/                       # Wrapper文件
├── common/                            # 公共模块
├── services/                          # 业务服务
├── infrastructure/                    # 基础设施
└── docs/                             # 文档
14.2 构建脚本最佳实践
// ✅ 推荐的构建脚本结构
plugins {
    // 插件声明
}

// 项目属性
group = 'com.example'
version = '1.0.0'

// 仓库配置
repositories {
    // 仓库声明
}

// 依赖配置
dependencies {
    // 依赖声明
}

// 任务配置
tasks.named('test') {
    // 任务配置
}

// 自定义任务
task customTask {
    // 任务定义
}
14.3 性能优化最佳实践
# gradle.properties 优化配置
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.caching=true
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g
14.4 版本管理最佳实践
// ✅ 使用版本目录
dependencyResolutionManagement {
    versionCatalogs {
        libs {
            library('spring-boot-starter-web', 'org.springframework.boot', 'spring-boot-starter-web').version('2.7.0')
            library('junit-jupiter', 'org.junit.jupiter', 'junit-jupiter').version('5.9.2')

            bundle('spring-boot', ['spring-boot-starter-web', 'spring-boot-starter-actuator'])
        }
    }
}

// 在构建脚本中使用
dependencies {
    implementation libs.spring.boot.starter.web
    testImplementation libs.junit.jupiter
    implementation libs.bundles.spring.boot
}

📚 总结与进阶学习

🎯 学习成果检验

通过本手册的学习,您应该掌握:

✅ 基础知识

  • Gradle的核心概念和优势
  • DSL语法和构建脚本编写
  • 任务系统和依赖管理
  • 插件使用和配置

✅ 进阶技能

  • 多项目构建管理
  • 自定义插件开发
  • 性能优化技巧
  • 企业级应用实践

✅ 实战能力

  • 能够设计和实现复杂的构建系统
  • 解决常见的构建问题
  • 优化构建性能
  • 遵循最佳实践

🚀 进阶学习建议

  1. 深入学习Gradle内部机制

    • 理解Gradle的构建生命周期
    • 学习任务图和依赖解析机制
  2. 企业级实践

    • 学习Gradle Enterprise的使用
    • 掌握大型项目的构建优化
  3. 生态系统集成

    • 学习与CI/CD系统的集成
    • 了解与Docker、Kubernetes的结合
  4. 插件生态

    • 探索丰富的Gradle插件生态
    • 学习编写高质量的自定义插件

📖 推荐资源


🎉 系列文章总结

通过上下两篇的深入学习,我们完整地探索了Gradle在现代企业级应用中的方方面面:

📚 上篇回顾

  • 🎯 基础概念:Gradle核心优势、安装配置、项目结构
  • 📝 DSL语法:Groovy/Kotlin DSL、构建脚本编写、语法特性
  • ⚙️ 任务系统:任务定义、依赖关系、输入输出管理
  • 🔍 依赖管理:配置类型、版本管理、冲突解决

📚 下篇精华

  • 🏗️ 多项目构建:项目结构设计、配置管理、构建策略
  • 🔌 插件开发:自定义插件、任务类、扩展开发
  • ⚡ 性能优化:构建缓存、并行构建、增量构建
  • 🎯 实战案例:微服务项目、企业级应用、最佳实践

🌟 核心价值

  • 现代化工具:体验比Maven更快更灵活的构建方式
  • 企业级实践:适用于大型复杂项目的构建管理
  • 性能导向:充分利用Gradle的性能优势
  • 生态丰富:强大的插件生态系统支持

通过这两篇文章的学习,相信您已经掌握了Gradle在现代企业级应用中的高级用法。Gradle作为新一代构建工具,正在被越来越多的企业采用。掌握这些技能将使您在技术道路上更具竞争力。


💡 持续学习:Gradle生态系统在快速发展,新的特性和最佳实践不断涌现。保持学习的热情,关注官方动态,将这些先进的构建管理思想应用到实际项目中,提升开发效率和项目质量。

🎉 恭喜您完成了Gradle全网最细学习手册的学习!现在您已经具备了使用Gradle进行现代化项目构建的专业能力。