作为构建作者,您可以定义任务并指定它们之间的依赖项。Gradle 保证任务将按照这些依赖项指定的顺序执行。
您的构建脚本和插件配置此任务依赖项图。
例如,如果您的项目包含诸如 build
、assemble
和 createDocs
等任务,您可以配置构建脚本,使其按照以下顺序执行:build
→ assemble
→ createDocs
。
构建阶段
Gradle 构建有三个不同的阶段。

Gradle 按顺序运行这些阶段
- 阶段 1. 初始化
- 阶段 2. 配置
-
-
评估参与构建的每个项目的构建脚本
build.gradle(.kts)
。 -
为请求的任务创建任务图。
-
- 阶段 3. 执行
-
-
调度并执行选定的任务。
-
任务之间的依赖项决定执行顺序。
-
任务的执行可以并行进行。
-

示例
以下示例显示了设置文件和构建文件的哪些部分对应于不同的构建阶段
settings.gradle.kts
rootProject.name = "basic"
println("This is executed during the initialization phase.")
build.gradle.kts
println("This is executed during the configuration phase.")
tasks.register("configured") {
println("This is also executed during the configuration phase, because :configured is used in the build.")
}
tasks.register("test") {
doLast {
println("This is executed during the execution phase.")
}
}
tasks.register("testBoth") {
doFirst {
println("This is executed first during the execution phase.")
}
doLast {
println("This is executed last during the execution phase.")
}
println("This is executed during the configuration phase as well, because :testBoth is used in the build.")
}
settings.gradle
rootProject.name = 'basic'
println 'This is executed during the initialization phase.'
build.gradle
println 'This is executed during the configuration phase.'
tasks.register('configured') {
println 'This is also executed during the configuration phase, because :configured is used in the build.'
}
tasks.register('test') {
doLast {
println 'This is executed during the execution phase.'
}
}
tasks.register('testBoth') {
doFirst {
println 'This is executed first during the execution phase.'
}
doLast {
println 'This is executed last during the execution phase.'
}
println 'This is executed during the configuration phase as well, because :testBoth is used in the build.'
}
以下命令执行上面指定的 test
和 testBoth
任务。因为 Gradle 只配置请求的任务及其依赖项,所以 configured
任务永远不会被配置。
> gradle test testBoth
This is executed during the initialization phase.
> Configure project :
This is executed during the configuration phase.
This is executed during the configuration phase as well, because :testBoth is used in the build.
> Task :test
This is executed during the execution phase.
> Task :testBoth
This is executed first during the execution phase.
This is executed last during the execution phase.
BUILD SUCCESSFUL in 0s
2 actionable tasks: 2 executed
> gradle test testBoth
This is executed during the initialization phase.
> Configure project :
This is executed during the configuration phase.
This is executed during the configuration phase as well, because :testBoth is used in the build.
> Task :test
This is executed during the execution phase.
> Task :testBoth
This is executed first during the execution phase.
This is executed last during the execution phase.
BUILD SUCCESSFUL in 0s
2 actionable tasks: 2 executed
阶段 1. 初始化
在初始化阶段,Gradle 检测参与构建的项目集(根项目和子项目)和包含的构建。
Gradle 首先评估设置文件 settings.gradle(.kts)
并实例化一个 Settings
对象。然后,Gradle 为每个项目实例化 Project
实例。
阶段 2. 配置
在配置阶段,Gradle 向初始化阶段发现的项目添加任务和其他属性。