身為建構作者,您定義工作和工作之間的相依性。Gradle 保證這些工作會按照其相依性順序執行。
您的建構指令碼和外掛會組態此相依性圖形。
例如,如果您的專案工作包含 build
、assemble
、createDocs
,您的建構指令碼可以確保它們按照 build
→ assemble
→ createDoc
順序執行。
建構階段
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 會將任務和其他屬性新增到初始化階段找到的專案。