身為建置作者,您可以定義工作並指定它們之間的相依性。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 將工作和其他屬性新增至初始化階段找到的專案。