📌 第一阶段:Gradle 基础概念与环境搭建

🎯 1. Gradle 是什么?深度解析

1.1 Gradle 的核心优势

Gradle是一个开源的构建自动化工具,专注于灵活性和性能。它结合了Ant的强大功能和Maven的依赖管理概念。

🔧 五大核心优势:

  1. 高性能:增量构建、构建缓存、并行执行
  2. 灵活性:基于Groovy/Kotlin DSL的强大脚本能力
  3. 可扩展性:丰富的插件生态系统
  4. 多语言支持:Java、Kotlin、Scala、C++、Python等
  5. 企业级特性:构建扫描、依赖洞察、性能分析
1.2 Gradle vs. Maven vs. Ant 详细对比
特性 Gradle Maven Ant
配置语言 Groovy/Kotlin DSL XML XML
构建性能 🥇 最快(增量构建+缓存) 🥉 较慢 🥈 中等
灵活性 🥇 极高(编程式配置) 🥉 较低(约定优于配置) 🥈 高(过程式)
学习曲线 🥈 中等偏陡 🥇 相对简单 🥉 复杂
依赖管理 🥇 强大且灵活 🥈 强大但固化 🥉 需手动管理
多项目支持 🥇 原生支持 🥈 通过聚合 🥉 需手动配置
IDE支持 🥇 优秀 🥇 优秀 🥈 一般
生态系统 🥈 快速发展 🥇 最成熟 🥉 逐渐衰落
企业采用 🥈 快速增长 🥇 最广泛 🥉 逐渐减少
1.3 Gradle 的核心概念

🎯 项目(Project)

  • 每个构建都包含一个或多个项目
  • 项目代表可以构建的组件(如JAR库、Web应用等)
  • 由build.gradle文件定义

🎯 任务(Task)

  • 构建的基本工作单元
  • 如编译代码、运行测试、创建JAR等
  • 任务之间可以有依赖关系

🎯 插件(Plugin)

  • 扩展Gradle功能的模块
  • 提供任务、约定和配置
  • 如Java插件、Spring Boot插件等

🎯 构建脚本(Build Script)

  • 使用Groovy或Kotlin DSL编写
  • 定义项目配置、依赖、任务等
  • 具有强大的编程能力

🛠️ 2. Gradle 安装与配置详解

2.1 安装方式对比

方式1:使用Gradle Wrapper(推荐)

1
2
3
4
5
6
7
8
# 优势:
# - 确保团队使用相同版本
# - 无需预安装Gradle
# - 自动下载指定版本

# 使用方式
./gradlew build # Linux/Mac
gradlew.bat build # Windows

方式2:手动安装

1
2
3
4
5
6
7
8
9
10
# 1. 下载Gradle
# 访问:https://gradle.org/releases/
# 下载:gradle-8.4-bin.zip

# 2. 解压并配置环境变量
export GRADLE_HOME=/opt/gradle/gradle-8.4
export PATH=$PATH:$GRADLE_HOME/bin

# 3. 验证安装
gradle --version

方式3:包管理器安装

1
2
3
4
5
6
7
8
9
10
11
# macOS (Homebrew)
brew install gradle

# Ubuntu/Debian
sudo apt install gradle

# Windows (Chocolatey)
choco install gradle

# Windows (Scoop)
scoop install gradle
2.2 Gradle Wrapper 详解

🔧 生成Wrapper

1
2
3
4
5
6
7
8
9
10
11
12
# 生成wrapper文件
gradle wrapper --gradle-version 8.4

# 生成的文件结构
project/
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew # Unix脚本
├── gradlew.bat # Windows脚本
└── build.gradle

📝 gradle-wrapper.properties配置

1
2
3
4
5
6
7
# Gradle Wrapper配置文件
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

🚀 Wrapper优化配置

1
2
3
4
5
6
7
8
9
10
11
# 使用国内镜像加速下载
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.4-bin.zip

# 或使用阿里云镜像
distributionUrl=https\://mirrors.aliyun.com/macports/distfiles/gradle/gradle-8.4-bin.zip

# 高级配置选项
networkTimeout=10000 # 网络超时时间(毫秒)
validateDistributionUrl=true # 验证下载URL
zipStoreBase=GRADLE_USER_HOME # ZIP存储基础目录
zipStorePath=wrapper/dists # ZIP存储路径

💡 Wrapper配置实战案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 案例1:企业内网环境配置
# 问题:公司内网无法访问外网,需要使用内部镜像
# 解决方案:
distributionUrl=https\://nexus.company.com/repository/gradle-distributions/gradle-8.4-bin.zip

# 案例2:开发团队版本统一
# 问题:团队成员使用不同Gradle版本导致构建不一致
# 解决方案:强制使用项目指定版本
./gradlew wrapper --gradle-version 8.4 --distribution-type bin

# 案例3:CI/CD环境优化
# 问题:CI环境每次都重新下载Gradle,浪费时间
# 解决方案:使用缓存友好的配置
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
# 在CI脚本中缓存 ~/.gradle 目录
2.3 Gradle 配置优化

📁 gradle.properties(项目级配置)详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# ==================== 构建性能优化 ====================
# 启用Gradle守护进程(推荐)
org.gradle.daemon=true
# 说明:守护进程可以避免JVM启动开销,显著提升构建速度
# 适用场景:开发环境必开,CI环境可选

# 启用并行构建(推荐)
org.gradle.parallel=true
# 说明:允许多个项目并行构建,充分利用多核CPU
# 适用场景:多模块项目效果明显

# 按需配置(谨慎使用)
org.gradle.configureondemand=true
# 说明:只配置需要的项目,减少配置时间
# 注意:可能导致某些插件工作异常,需要测试

# 启用构建缓存(强烈推荐)
org.gradle.caching=true
# 说明:缓存任务输出,避免重复执行
# 效果:可以将构建时间减少50-90%

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

# 详细JVM参数说明:
# -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

# ==================== 网络和代理设置 ====================
# 编码设置
systemProp.file.encoding=UTF-8

# HTTP代理设置
systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=username
systemProp.http.proxyPassword=password

# HTTPS代理设置
systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=username
systemProp.https.proxyPassword=password

# 非代理主机(多个用|分隔)
systemProp.http.nonProxyHosts=localhost|127.0.0.1|*.company.com

# ==================== 构建行为控制 ====================
# 控制台输出模式
org.gradle.console=rich
# 可选值:auto, plain, rich, verbose

# 日志级别
org.gradle.logging.level=lifecycle
# 可选值:quiet, warn, lifecycle, info, debug

# 警告模式
org.gradle.warning.mode=all
# 可选值:all, fail, summary, none

# ==================== 项目特定配置 ====================
# 应用版本
version=1.0.0-SNAPSHOT

# 自定义属性
app.name=MyApplication
app.description=My Gradle Application
app.mainClass=com.example.Application

# 数据库配置(开发环境)
db.url=jdbc:mysql://localhost:3306/myapp
db.username=dev_user
db.password=dev_password

# 构建配置
build.timestamp=${new Date().format('yyyy-MM-dd HH:mm:ss')}

🏠 ~/.gradle/gradle.properties(全局配置)详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# ==================== 全局性能设置 ====================
# 全局JVM设置(适用于所有项目)
org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC

# 全局并行构建
org.gradle.parallel=true

# 全局构建缓存
org.gradle.caching=true

# 全局守护进程设置
org.gradle.daemon=true

# ==================== 全局网络设置 ====================
# 全局代理设置(适用于所有项目)
systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080

# ==================== 认证信息 ====================
# Gradle Wrapper认证(私有仓库)
systemProp.gradle.wrapperUser=username
systemProp.gradle.wrapperPassword=password

# 仓库认证信息
nexusUsername=your_username
nexusPassword=your_password

# 签名密钥信息
signing.keyId=12345678
signing.password=your_signing_password
signing.secretKeyRingFile=/Users/username/.gnupg/secring.gpg

# ==================== 开发者个人设置 ====================
# 开发者信息
developer.name=John Doe
developer.email=john.doe@company.com
developer.organization=My Company

# 个人偏好设置
org.gradle.console=rich
org.gradle.warning.mode=all

💡 全局配置实战案例

案例1:企业开发环境统一配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ~/.gradle/gradle.properties
# 企业统一JVM设置
org.gradle.jvmargs=-Xmx6g -XX:MaxMetaspaceSize=512m -XX:+UseG1GC

# 企业代理设置
systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080
systemProp.http.nonProxyHosts=*.company.com|localhost

# 企业仓库认证
nexusUsername=${env.NEXUS_USERNAME}
nexusPassword=${env.NEXUS_PASSWORD}

# 开发者信息
developer.name=${env.USER}
developer.email=${env.USER}@company.com

案例2:个人开发机优化配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ~/.gradle/gradle.properties
# 个人机器性能优化(16GB内存)
org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC -XX:+UseStringDeduplication

# 最大化并行度
org.gradle.parallel=true
org.gradle.workers.max=8

# 启用所有缓存
org.gradle.caching=true
org.gradle.configuration-cache=true

# 详细输出(开发调试用)
org.gradle.console=verbose
org.gradle.logging.level=info

案例3:CI/CD环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ~/.gradle/gradle.properties (CI环境)
# CI环境JVM设置
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m

# CI环境优化
org.gradle.daemon=false # CI环境不使用守护进程
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 项目结构深度解析

3.1 标准项目结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
my-gradle-project/
├── build.gradle(.kts) # 构建脚本
├── settings.gradle(.kts) # 设置脚本
├── gradle.properties # 项目属性
├── gradlew # Wrapper脚本(Unix)
├── gradlew.bat # Wrapper脚本(Windows)
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── src/
│ ├── main/
│ │ ├── java/ # Java源代码
│ │ ├── kotlin/ # Kotlin源代码
│ │ ├── resources/ # 资源文件
│ │ └── webapp/ # Web资源(Web项目)
│ ├── test/
│ │ ├── java/ # 测试代码
│ │ ├── kotlin/ # Kotlin测试代码
│ │ └── resources/ # 测试资源
│ └── integrationTest/ # 集成测试(可选)
├── build/ # 构建输出目录
│ ├── classes/
│ ├── libs/
│ ├── reports/
│ └── tmp/
└── README.md
3.2 核心文件详解

📋 build.gradle 基础结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 插件配置
plugins {
id 'java'
id 'application'
id 'org.springframework.boot' version '2.7.0'
}

// 项目基本信息
group = 'com.example'
version = '1.0.0'
sourceCompatibility = '11'

// 仓库配置
repositories {
mavenCentral()
gradlePluginPortal()
}

// 依赖配置
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.junit.jupiter:junit-jupiter'
}

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

// 应用配置
application {
mainClass = 'com.example.Application'
}

⚙️ settings.gradle 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 根项目名称
rootProject.name = 'my-gradle-project'

// 包含子项目
include 'subproject1', 'subproject2'

// 插件管理
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}

// 依赖解析管理
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
}
}
3.3 创建Gradle项目

方法1:使用Gradle init(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
# 创建Java应用项目
gradle init --type java-application --dsl groovy --test-framework junit-jupiter

# 创建Java库项目
gradle init --type java-library --dsl kotlin --test-framework spock

# 创建Spring Boot项目
gradle init --type java-application --dsl groovy
# 然后手动添加Spring Boot插件

# 交互式创建
gradle init

方法2:手动创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 创建项目目录
mkdir my-gradle-project && cd my-gradle-project

# 创建标准目录结构
mkdir -p src/main/java/com/example
mkdir -p src/main/resources
mkdir -p src/test/java/com/example
mkdir -p src/test/resources

# 创建构建脚本
touch build.gradle
touch settings.gradle
touch gradle.properties

# 生成Wrapper
gradle wrapper --gradle-version 8.4

📝 最小化build.gradle示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
id 'java'
}

repositories {
mavenCentral()
}

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

tasks.named('test') {
useJUnitPlatform()
}

📌 第二阶段:Gradle DSL 语法与构建脚本

📝 4. Groovy DSL 深度解析

4.1 Groovy DSL 基础语法

🎯 基本语法特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 1. 方法调用可以省略括号
println 'Hello Gradle'
println('Hello Gradle') // 等价

// 2. 字符串插值
def version = '1.0.0'
println "Current version: ${version}"
println "Current version: $version" // 简化形式

// 3. 闭包(Closure)
def myClosure = { param ->
println "Parameter: $param"
}
myClosure('test')

// 4. 集合操作
def list = ['java', 'kotlin', 'scala']
list.each { language ->
println "Language: $language"
}

// 5. Map操作
def config = [
version: '1.0.0',
encoding: 'UTF-8'
]
println config.version

🔧 Gradle DSL 核心概念

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 1. 配置块(Configuration Block)
android {
compileSdkVersion 33
defaultConfig {
applicationId "com.example.app"
minSdkVersion 21
}
}

// 2. 任务配置
task myTask {
doLast {
println 'Executing myTask'
}
}

// 3. 依赖配置
dependencies {
implementation 'org.springframework:spring-core:5.3.21'
testImplementation 'junit:junit:4.13.2'
}

// 4. 属性访问
project.version = '1.0.0'
version = '1.0.0' // 简化形式
4.2 构建脚本结构详解

📋 完整的build.gradle结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// ==================== 1. 插件配置 ====================
plugins {
// 核心插件
id 'java'
id 'application'

// 社区插件
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'

// 条件应用插件
if (project.hasProperty('android')) {
id 'com.android.application'
}
}

// ==================== 2. 项目属性 ====================
group = 'com.example'
version = '1.0.0-SNAPSHOT'
description = 'My Gradle Project'

// Java配置
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
withJavadocJar()
withSourcesJar()
}

// ==================== 3. 仓库配置详解 ====================
repositories {
// 仓库优先级:从上到下依次查找

// 1. 本地Maven仓库(最快)
mavenLocal()
// 位置:~/.m2/repository
// 优势:本地缓存,访问最快
// 注意:可能包含SNAPSHOT版本,生产环境需谨慎

// 2. Maven中央仓库(最权威)
mavenCentral()
// 地址:https://repo1.maven.org/maven2/
// 优势:官方仓库,最可靠
// 包含:大部分开源项目的正式版本

// 3. Gradle插件门户
gradlePluginPortal()
// 地址:https://plugins.gradle.org/
// 用途:Gradle插件专用仓库

// 4. 国内镜像仓库(加速访问)
maven {
name = 'Aliyun'
url = 'https://maven.aliyun.com/repository/public'
// 优势:国内访问速度快
// 适用:开发环境加速下载
}

// 5. 特定用途仓库
maven {
name = 'Spring Milestones'
url = 'https://repo.spring.io/milestone'
// 内容过滤:只包含Spring相关依赖
mavenContent {
includeGroupByRegex 'org\\.springframework.*'
includeGroup 'org.springframework.boot'
includeGroup 'org.springframework.cloud'
}
}

// 6. 企业私有仓库(需要认证)
maven {
name = 'CompanyNexus'
url = 'https://nexus.company.com/repository/maven-public/'
credentials {
// 从gradle.properties读取认证信息
username = project.findProperty('nexusUsername') ?: 'guest'
password = project.findProperty('nexusPassword') ?: 'guest'
}
// 认证方式
authentication {
basic(BasicAuthentication)
}
}

// 7. SNAPSHOT仓库
maven {
name = 'CompanySnapshots'
url = 'https://nexus.company.com/repository/maven-snapshots/'
credentials {
username = project.findProperty('nexusUsername')
password = project.findProperty('nexusPassword')
}
// 只包含SNAPSHOT版本
mavenContent {
snapshotsOnly()
}
}

// 8. 条件仓库(根据环境决定)
if (project.hasProperty('useInternalRepo')) {
maven {
name = 'InternalRepo'
url = 'https://internal.company.com/repository/'
}
}
}

// 仓库配置最佳实践案例
repositories {
// 开发环境:优先使用本地和镜像
if (project.hasProperty('dev')) {
mavenLocal()
maven { url 'https://maven.aliyun.com/repository/public' }
mavenCentral()
}
// 生产环境:只使用可靠仓库
else {
mavenCentral()
maven {
url 'https://nexus.company.com/repository/maven-public/'
credentials {
username nexusUsername
password nexusPassword
}
}
}
}

// ==================== 4. 依赖配置 ====================
// 版本管理
ext {
springBootVersion = '2.7.0'
junitVersion = '5.9.2'
mockitoVersion = '4.11.0'
}

dependencies {
// ==================== 编译时依赖 ====================
// implementation: 编译和运行时需要,但不传递给消费者
implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
// 说明:Spring Boot Web启动器,包含Spring MVC、Tomcat等
// 使用场景:Web应用开发的核心依赖

implementation 'org.apache.commons:commons-lang3:3.12.0'
// 说明:Apache Commons工具库,提供字符串、数组等工具方法
// 使用场景:日常开发中的工具类需求

implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3'
// 说明:JSON序列化/反序列化库
// 使用场景:API数据交换、配置文件解析

// ==================== 编译时专用依赖 ====================
// compileOnly: 编译时需要,运行时由容器或环境提供
compileOnly 'javax.servlet:javax.servlet-api:4.0.1'
// 说明:Servlet API,运行时由Tomcat等容器提供
// 使用场景:Web应用开发,避免与容器版本冲突

compileOnly 'org.projectlombok:lombok:1.18.24'
// 说明:Lombok注解处理器,编译时生成代码
// 使用场景:减少样板代码,如getter/setter

// ==================== 运行时依赖 ====================
// runtimeOnly: 运行时需要,编译时不需要
runtimeOnly 'mysql:mysql-connector-java:8.0.33'
// 说明:MySQL数据库驱动
// 使用场景:数据库连接,编译时不直接使用

runtimeOnly 'com.h2database:h2:2.1.214'
// 说明:H2内存数据库
// 使用场景:开发和测试环境的轻量级数据库

// ==================== 注解处理器 ====================
// annotationProcessor: 编译时注解处理
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
// 说明:Spring Boot配置元数据生成器
// 作用:为@ConfigurationProperties生成元数据,支持IDE自动补全

annotationProcessor 'org.projectlombok:lombok:1.18.24'
// 说明:Lombok注解处理器
// 作用:编译时生成getter、setter、toString等方法

// ==================== 测试依赖 ====================
// testImplementation: 测试编译和运行时需要
testImplementation "org.junit.jupiter:junit-jupiter:${junitVersion}"
// 说明:JUnit 5测试框架
// 使用场景:单元测试、集成测试

testImplementation "org.mockito:mockito-core:${mockitoVersion}"
// 说明:Mock框架,用于创建测试替身
// 使用场景:单元测试中模拟依赖对象

testImplementation 'org.springframework.boot:spring-boot-starter-test'
// 说明:Spring Boot测试启动器,包含多个测试库
// 包含:JUnit、Mockito、AssertJ、Hamcrest等

testImplementation 'org.testcontainers:junit-jupiter:1.17.3'
// 说明:Testcontainers集成测试框架
// 使用场景:使用Docker容器进行集成测试

testImplementation 'org.testcontainers:mysql:1.17.3'
// 说明:MySQL Testcontainer
// 使用场景:数据库集成测试

// ==================== 测试运行时依赖 ====================
// testRuntimeOnly: 测试运行时需要,测试编译时不需要
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
// 说明:JUnit平台启动器
// 作用:IDE和构建工具运行测试时需要
}

// ==================== 依赖配置实战案例 ====================

// 案例1:Spring Boot Web应用完整依赖配置
dependencies {
// Web层
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'

// 数据层
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'mysql:mysql-connector-java'

// 安全
implementation 'org.springframework.boot:spring-boot-starter-security'

// 监控
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-registry-prometheus'

// 工具类
implementation 'org.apache.commons:commons-lang3'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

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

// 案例2:微服务项目依赖配置
dependencies {
// 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'

// 服务间通信
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'

// 消息队列
implementation 'org.springframework.boot:spring-boot-starter-amqp'

// 缓存
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

// 基础依赖
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
}

// ==================== 5. 任务配置 ====================
// 测试配置
tasks.named('test') {
useJUnitPlatform()

// 测试JVM参数
jvmArgs = ['-Xmx1024m']

// 系统属性
systemProperty 'spring.profiles.active', 'test'

// 测试报告
reports {
html.required = true
junitXml.required = true
}

// 测试事件监听
testLogging {
events 'passed', 'skipped', 'failed'
exceptionFormat = 'full'
}
}

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

// JAR配置
jar {
manifest {
attributes(
'Implementation-Title': project.name,
'Implementation-Version': project.version,
'Main-Class': 'com.example.Application'
)
}

// 排除文件
exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA'
}

// ==================== 6. 自定义任务 ====================
task printProjectInfo {
group = 'help'
description = '打印项目信息'

doLast {
println "Project: ${project.name}"
println "Version: ${project.version}"
println "Java Version: ${java.sourceCompatibility}"
println "Dependencies: ${configurations.runtimeClasspath.files.size()}"
}
}

// ==================== 7. 应用配置 ====================
application {
mainClass = 'com.example.Application'
applicationDefaultJvmArgs = ['-Xmx512m']
}

// ==================== 8. 发布配置 ====================
publishing {
publications {
maven(MavenPublication) {
from components.java

pom {
name = project.name
description = project.description
url = 'https://github.com/example/my-project'

licenses {
license {
name = 'Apache License 2.0'
url = 'https://www.apache.org/licenses/LICENSE-2.0'
}
}

developers {
developer {
id = 'johndoe'
name = 'John Doe'
email = 'john@example.com'
}
}
}
}
}

repositories {
maven {
name = 'CompanyNexus'
url = version.endsWith('SNAPSHOT') ?
'https://nexus.company.com/repository/maven-snapshots/' :
'https://nexus.company.com/repository/maven-releases/'
credentials {
username = project.findProperty('nexusUsername')
password = project.findProperty('nexusPassword')
}
}
}
}
4.3 Kotlin DSL 对比

📝 build.gradle.kts 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Kotlin DSL语法
plugins {
java
application
id("org.springframework.boot") version "2.7.0"
}

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

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

repositories {
mavenCentral()
}

dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
}

tasks.named<Test>("test") {
useJUnitPlatform()
}

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

🔍 Groovy vs Kotlin DSL 对比

特性 Groovy DSL Kotlin DSL
语法 动态、简洁 静态类型、严格
IDE支持 基础支持 优秀的代码补全和重构
性能 运行时解析 编译时检查
学习曲线 较平缓 需要Kotlin知识
错误检测 运行时 编译时
重构支持 有限 强大

🔍 5. 依赖管理深度实践

5.1 依赖配置详解

📦 依赖配置类型

配置 说明 编译时 运行时 测试时 传递性
implementation 实现依赖(推荐)
api API依赖
compileOnly 仅编译时
runtimeOnly 仅运行时
testImplementation 测试实现
testCompileOnly 测试编译时
testRuntimeOnly 测试运行时

🔧 实际应用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
dependencies {
// implementation: 内部实现,不暴露给消费者
implementation 'org.springframework:spring-core:5.3.21'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3'

// api: 公共API,会传递给消费者(仅在java-library插件中可用)
api 'org.apache.commons:commons-lang3:3.12.0'

// compileOnly: 编译时需要,运行时由容器提供
compileOnly 'javax.servlet:javax.servlet-api:4.0.1'
compileOnly 'org.projectlombok:lombok:1.18.24'

// runtimeOnly: 运行时依赖,如数据库驱动
runtimeOnly 'mysql:mysql-connector-java:8.0.33'
runtimeOnly 'com.h2database:h2:2.1.214'

// annotationProcessor: 注解处理器
annotationProcessor 'org.projectlombok:lombok:1.18.24'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'

// 测试依赖
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
testImplementation 'org.mockito:mockito-core:4.11.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

// 测试运行时
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
5.2 版本管理策略

🎯 版本声明方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
dependencies {
// 1. 直接指定版本
implementation 'org.springframework:spring-core:5.3.21'

// 2. 使用变量管理版本
implementation "org.springframework:spring-core:${springVersion}"

// 3. 使用ext属性
implementation "org.springframework:spring-core:${ext.springVersion}"

// 4. 版本范围(不推荐生产环境)
implementation 'org.springframework:spring-core:5.+'
implementation 'org.springframework:spring-core:[5.0,6.0)'

// 5. 最新版本(不推荐)
implementation 'org.springframework:spring-core:latest.release'
}

// 版本管理最佳实践
ext {
springVersion = '5.3.21'
junitVersion = '5.9.2'
mockitoVersion = '4.11.0'
}

// 或使用gradle.properties
// springVersion=5.3.21
// junitVersion=5.9.2

🔧 依赖约束和BOM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 使用Spring Boot BOM
dependencies {
// 导入BOM
implementation platform('org.springframework.boot:spring-boot-dependencies:2.7.0')

// 无需指定版本,由BOM管理
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

// 覆盖BOM版本
implementation 'com.fasterxml.jackson.core:jackson-core:2.14.0'
}

// 自定义依赖约束
dependencyManagement {
dependencies {
dependency 'org.apache.commons:commons-lang3:3.12.0'
dependency 'com.google.guava:guava:31.1-jre'
}
}
5.3 依赖冲突解决

🔍 查看依赖树

1
2
3
4
5
6
7
8
9
10
11
# 查看所有依赖
./gradlew dependencies

# 查看特定配置的依赖
./gradlew dependencies --configuration runtimeClasspath

# 查看依赖洞察
./gradlew dependencyInsight --dependency spring-core

# 查看依赖冲突
./gradlew dependencies --configuration runtimeClasspath | grep "(*)"

🛠️ 解决冲突策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
dependencies {
implementation 'org.springframework:spring-core:5.3.21'

// 1. 排除传递依赖
implementation('org.springframework:spring-context:5.3.21') {
exclude group: 'commons-logging', module: 'commons-logging'
}

// 2. 排除所有传递依赖
implementation('some.group:some-module:1.0') {
transitive = false
}

// 3. 强制使用特定版本
implementation 'commons-logging:commons-logging:1.2'
}

// 全局依赖解析策略
configurations.all {
resolutionStrategy {
// 强制使用特定版本
force 'commons-logging:commons-logging:1.2'

// 版本冲突时失败
failOnVersionConflict()

// 缓存动态版本
cacheDynamicVersionsFor 10, 'minutes'
cacheChangingModulesFor 4, 'hours'

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

📌 第三阶段:Gradle 任务系统与插件

⚙️ 6. 任务系统深度解析

6.1 任务基础概念

🎯 任务的生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 任务定义阶段
task myTask {
// 配置阶段执行
println 'Configuring myTask'

// 执行阶段
doFirst {
println 'Before myTask execution'
}

doLast {
println 'After myTask execution'
}
}

// 任务配置
myTask {
description = 'My custom task'
group = 'custom'
}

🔧 任务类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 1. Ad-hoc任务(简单任务)
task hello {
doLast {
println 'Hello, Gradle!'
}
}

// 2. 类型化任务
task copyFiles(type: Copy) {
from 'src/main/resources'
into 'build/resources'
}

task createZip(type: Zip) {
from 'src/main/java'
archiveFileName = 'sources.zip'
destinationDirectory = file('build/distributions')
}

// 3. 自定义任务类
class GreetingTask extends DefaultTask {
@Input
String greeting = 'hello'

@Input
String recipient = 'world'

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

task greeting(type: GreetingTask) {
greeting = 'Hi'
recipient = 'Gradle'
}
6.2 任务依赖与排序

🔗 任务依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
task taskA {
doLast {
println 'Task A'
}
}

task taskB {
doLast {
println 'Task B'
}
}

task taskC {
// 依赖taskA和taskB
dependsOn taskA, taskB
doLast {
println 'Task C'
}
}

// 动态依赖
task taskD {
dependsOn tasks.matching { task -> task.name.startsWith('test') }
doLast {
println 'Task D'
}
}

// 条件依赖
taskC.dependsOn {
tasks.findAll { task -> task.name.startsWith('compile') && task.enabled }
}

📋 任务排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
task taskX {
doLast { println 'Task X' }
}

task taskY {
doLast { println 'Task Y' }
}

// mustRunAfter: 如果两个任务都要执行,确保顺序
taskY.mustRunAfter taskX

// shouldRunAfter: 软排序,尽量保证顺序
taskY.shouldRunAfter taskX

// finalizedBy: 无论成功失败都会执行
task cleanup {
doLast { println 'Cleanup' }
}

taskX.finalizedBy cleanup
6.3 任务输入输出

📁 任务输入输出管理详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// ==================== 基础输入输出配置 ====================
task processFiles {
// 输入文件配置
inputs.files fileTree('src/main/resources') {
include '**/*.properties'
include '**/*.yml'
exclude '**/*.tmp'
}

// 输入属性配置
inputs.property 'version', project.version
inputs.property 'environment', project.findProperty('env') ?: 'dev'

// 输出目录配置
outputs.dir 'build/processed'

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

// 增量构建配置
outputs.upToDateWhen {
// 自定义最新检查逻辑
file('build/processed').exists() &&
file('build/processed').lastModified() > inputs.files.asFileTree.maxBy { it.lastModified() }.lastModified()
}

doLast {
// 确保输出目录存在
outputs.files.singleFile.mkdirs()

// 处理文件
copy {
from inputs.files
into outputs.files.singleFile
filter { line ->
line.replace('${version}', project.version)
.replace('${env}', project.findProperty('env') ?: 'dev')
}
}

println "Processed ${inputs.files.files.size()} files to ${outputs.files.singleFile}"
}
}

// ==================== 使用注解的任务类 ====================
class ProcessFilesTask extends DefaultTask {

// 输入文件:支持增量构建
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
FileCollection inputFiles

// 输入属性:影响任务执行结果
@Input
String version

@Input
@Optional
String environment = 'dev'

// 输出目录:任务的产出
@OutputDirectory
File outputDir

// 内部属性:不影响任务最新状态
@Internal
String logLevel = 'INFO'

@TaskAction
void processFiles() {
// 确保输出目录存在
outputDir.mkdirs()

// 处理每个输入文件
inputFiles.each { file ->
def outputFile = new File(outputDir, file.name)

outputFile.text = file.text
.replace('${version}', version)
.replace('${environment}', environment)

if (logLevel == 'DEBUG') {
println "Processed: ${file.name} -> ${outputFile.name}"
}
}

println "Processed ${inputFiles.files.size()} files for environment: ${environment}"
}
}

// 注册自定义任务
tasks.register('processConfigFiles', ProcessFilesTask) {
inputFiles = fileTree('src/main/resources/config')
version = project.version
environment = project.findProperty('env') ?: 'dev'
outputDir = file('build/processed-config')
}

// ==================== 复杂任务输入输出示例 ====================
task generateDocumentation {
// 多种输入类型
inputs.files fileTree('src/main/java') {
include '**/*.java'
}
inputs.files fileTree('docs/templates')
inputs.property 'version', project.version
inputs.property 'buildTime', new Date().format('yyyy-MM-dd HH:mm:ss')

// 多个输出
outputs.dir 'build/docs/api'
outputs.dir 'build/docs/user-guide'
outputs.file 'build/docs/README.html'

// 缓存配置
outputs.cacheIf {
// 只有在生产环境才缓存文档生成
project.hasProperty('prod')
}

doLast {
// 生成API文档
exec {
commandLine 'javadoc', '-d', 'build/docs/api',
'-sourcepath', 'src/main/java',
'-subpackages', 'com.example'
}

// 生成用户指南
copy {
from 'docs/templates'
into 'build/docs/user-guide'
expand(
version: project.version,
buildTime: new Date().format('yyyy-MM-dd HH:mm:ss')
)
}

// 生成README
def readmeContent = """
# ${project.name} v${project.version}

Generated on: ${new Date().format('yyyy-MM-dd HH:mm:ss')}

## API Documentation
See [API Docs](api/index.html)

## User Guide
See [User Guide](user-guide/index.html)
""".stripIndent()

file('build/docs/README.html').text = readmeContent
}
}

// ==================== 任务输入输出最佳实践 ====================

// 1. 文件复制任务
task copyResources(type: Copy) {
from 'src/main/resources'
into 'build/resources'

// 输入输出自动配置
// inputs.files 自动设置为 from 的文件
// outputs.dir 自动设置为 into 的目录

// 文件过滤
filter { line ->
line.replace('${project.version}', project.version)
}

// 包含/排除文件
include '**/*.properties'
exclude '**/*.tmp'
}

// 2. ZIP打包任务
task createDistribution(type: Zip) {
archiveFileName = "${project.name}-${project.version}.zip"
destinationDirectory = file('build/distributions')

from 'build/libs'
from 'src/main/scripts'
from 'README.md'

// 自动配置输入输出
// inputs 包含所有 from 的文件
// outputs.file 为生成的ZIP文件
}

// 3. 测试任务配置
tasks.named('test') {
// 输入配置
inputs.files sourceSets.test.runtimeClasspath
inputs.files sourceSets.main.runtimeClasspath
inputs.property 'javaVersion', System.getProperty('java.version')

// 输出配置
outputs.dir 'build/test-results'
outputs.dir 'build/reports/tests'

// 缓存配置
outputs.cacheIf {
// 只有在没有系统属性变化时才缓存
!project.hasProperty('rerunTests')
}
}

🔌 7. 插件系统详解

7.1 插件应用方式

📦 插件应用语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 1. 核心插件(推荐)
plugins {
id 'java'
id 'application'
}

// 2. 社区插件
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

// 3. 传统方式(不推荐)
apply plugin: 'java'
apply plugin: 'application'

// 4. 条件应用
plugins {
id 'java'
if (project.hasProperty('android')) {
id 'com.android.application'
}
}

// 5. 脚本插件
apply from: 'gradle/dependencies.gradle'
apply from: 'https://raw.githubusercontent.com/example/scripts/main/common.gradle'
7.2 常用插件详解

☕ Java插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
plugins {
id 'java'
}

// Java插件配置
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11

// 生成源码jar
withSourcesJar()

// 生成javadoc jar
withJavadocJar()
}

// 编译配置
compileJava {
options.encoding = 'UTF-8'
options.compilerArgs += ['-parameters', '-Xlint:unchecked']
}

// 测试配置
test {
useJUnitPlatform()

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

reports {
html.required = true
junitXml.required = true
}
}

🌐 Application插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
plugins {
id 'application'
}

application {
mainClass = 'com.example.Application'
applicationDefaultJvmArgs = ['-Xmx512m', '-Dfile.encoding=UTF-8']
}

// 生成的任务
// run: 运行应用
// distZip: 创建ZIP分发包
// distTar: 创建TAR分发包
// installDist: 安装应用到build/install

🌸 Spring Boot插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

springBoot {
buildInfo()

mainClass = 'com.example.Application'
}

// 生成的任务
// bootRun: 运行Spring Boot应用
// bootJar: 创建可执行JAR
// bootBuildImage: 构建Docker镜像

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

🏗️ 8. 多项目构建管理

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

8.1 多项目结构设计

📁 典型多项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 详细配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// ==================== 项目基本信息 ====================
// 根项目名称:影响生成的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:大型企业项目配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 企业级多模块项目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:开源项目配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 开源项目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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 应用于所有项目的配置
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 公共工具模块
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 多项目构建命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 构建所有项目
./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 插件开发方式

📝 脚本插件(简单场景)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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插件(项目级插件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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
}
}

🎯 独立插件项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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 插件实现示例

🎯 自定义任务类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 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
}
}
}

🔌 插件主类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 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'
}

📝 使用自定义插件

1
2
3
4
5
6
7
8
9
// build.gradle
plugins {
id 'com.example.my-plugin' version '1.0.0'
}

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

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

10.1 构建性能优化

🚀 Gradle Daemon优化详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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:开发环境优化配置

1
2
3
4
5
6
7
8
9
10
11
# ~/.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环境配置

1
2
3
4
5
6
7
8
9
10
11
# 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:容器环境配置

1
2
3
4
5
6
# 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 # 限制工作线程数

🔄 并行构建优化

1
2
3
4
5
6
7
8
9
# gradle.properties
# 启用并行构建
org.gradle.parallel=true

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

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

💾 构建缓存优化详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# 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:企业级缓存配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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:开源项目缓存配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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:多环境缓存策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 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 环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# ==================== 基础配置 ====================
# 项目基本信息
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 环境配置处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// ==================== 环境配置处理 ====================
// 环境检测
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 配置文件管理策略

📁 配置文件结构

1
2
3
4
5
6
7
8
9
10
11
12
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 模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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:多环境构建脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 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多环境构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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'
}
}

📊 增量构建优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 正确配置任务输入输出
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 依赖解析优化

🔍 依赖解析策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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')
}
}
}

📦 仓库优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 构建脚本优化

🎯 避免配置时间过长

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// ❌ 避免在配置阶段执行耗时操作
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()
}
}

🔧 任务配置优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ✅ 使用任务配置避免
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 项目结构设计
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 微服务约定插件
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 基础构建命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 基础命令
./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 性能分析命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 构建性能分析
./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 任务管理命令
1
2
3
4
5
6
7
8
9
10
11
12
13
# 任务查看
./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:构建缓存问题

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

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

❌ 问题2:依赖解析失败

1
2
3
4
5
6
7
# 症状:Could not resolve dependency
# 解决方案:
./gradlew dependencies --refresh-dependencies
./gradlew build --refresh-dependencies

# 检查仓库配置
./gradlew buildEnvironment

❌ 问题3:内存不足

1
2
3
4
5
6
7
# 症状:OutOfMemoryError
# 解决方案:调整gradle.properties
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g

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

❌ 问题4:Daemon问题

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

🔍 构建脚本调试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 添加调试输出
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"
}

📊 性能分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 任务执行时间统计
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 项目结构最佳实践
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ✅ 推荐的多项目结构
my-gradle-project/
├── settings.gradle # 项目设置
├── build.gradle # 根构建脚本
├── gradle.properties # 项目属性
├── buildSrc/ # 构建逻辑
│ ├── build.gradle
│ └── src/main/groovy/
├── gradle/
│ └── wrapper/ # Wrapper文件
├── common/ # 公共模块
├── services/ # 业务服务
├── infrastructure/ # 基础设施
└── docs/ # 文档
14.2 构建脚本最佳实践
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ✅ 推荐的构建脚本结构
plugins {
// 插件声明
}

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

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

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

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

// 自定义任务
task customTask {
// 任务定义
}
14.3 性能优化最佳实践
1
2
3
4
5
6
# 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 版本管理最佳实践
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ✅ 使用版本目录
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核心优势、安装配置、项目结构

  • 📝 DSL语法:Groovy/Kotlin DSL、构建脚本编写、语法特性

  • ⚙️ 任务系统:任务定义、依赖关系、输入输出管理

  • 🔍 依赖管理:配置类型、版本管理、冲突解决

  • 🏗️ 多项目构建:项目结构设计、配置管理、构建策略

  • 🔌 插件开发:自定义插件、任务类、扩展开发

  • ⚡ 性能优化:构建缓存、并行构建、增量构建

  • 🎯 实战案例:微服务项目、企业级应用、最佳实践

🌟 核心价值

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

本站由 卡卡龙 使用 Stellar 1.29.1主题创建

本站访问量 次. 本文阅读量 次.