我嘗試了定義任務的兩個版本:
版本 1:
tasks {
task helloWorld {
group 'Testing'
description "I don't do very much."
println "I can print in configuration phase, too. I'm a big boy."
doFirst {
println 'Hello'
}
doLast {
println "world"
}
}
}
版本 2:
task helloWorld {
group 'Testing'
description "I don't do very much."
println "I can print in configuration phase, too. I'm a big boy."
doFirst {
println 'Hello'
}
doLast {
println "world"
}
}
有什么區別嗎?在我看來,版本 1 比版本 2 更干凈,尤其是處理多個自定義任務和使用通用約定 ( https://docs.gradle.org/current/samples/sample_convention_plugins.html )。
我想確定,我沒有破壞任何東西,因為我從未在任何來源中看到版本 1。
uj5u.com熱心網友回復:
簡短的回答
- 兩個版本非常相似并且行為相同,但它們都使用“舊”任務 API,急切地創建任務;您應該考慮切換到“新”API (自 Gradle 4.9 起)
TaskContainer.register(...)
并使用方法懶惰地配置任務 - 版本 1 對您來說可能看起來更干凈,但實際上它比版本 2 更令人困惑,我將解釋原因。
長答案
舊任務 API 與新任務 API
在這兩個版本中,您都使用簡寫符號task myTask { /* task configuration closure */ }
,它是TaskContainer.create()方法的快捷方式:
// following is equivalent to:
// project.getTasks().create(...).configure( { /* tasks configuration */} )
tasks.create("myTask ") {
// task configuration closure
}
- 此表示法特定于 Groovy DSL,并且可能會在未來的 Gradle 版本中被棄用 - 在新的 Tasks API 中不會替代此表示法(請參閱此處和此處的更多資訊)
- 您應該更好地使用任務配置避免功能并懶惰地宣告您的自定義任務
版本 1 與版本 2
版本 2 是 Gradle 檔案建議在舊版本中宣告任務的方式,例如Gradle 5.6 中的 Helloworld (在最新版本中,檔案參考了新 API:Gradle 7.5 中的 Helloworld)
在您的版本 1 中:有兩個問題
tasks
財產沖突
project.tasks
由于動態專案屬性,可以參考Project.getTasks(): TaskContainer
屬性或任務:tasks
tasks {
// here we don't configure the project.TaskContainer as we could expect, but instead the default task named 'tasks'
// proof:
println " configuring task named: " it.name
// => configuring task named: tasks
println " type of current object beeing configured: " it.class.name
// => type of current object beeing configured: org.gradle.api.tasks.diagnostics.TaskReportTask_Decorated
// this will still work, thanks to Groovy closure delegate feature :
// will delegate to parent Project instance => equivalent to project.task("helloWorld3") { /* config */ }
task helloWorld3 {
// tasks configuration
}
}
有趣(或不有趣):由于委托機制,這也可以作業:
repositories {
task helloWorldDefinedInRepositories {
// tasks configuration
}
}
dependencies {
task helloWorldDefinedInDependencies {
// tasks configuration
}
}
tasks
(TaskContainer) 方法
您可以將自定義任務宣告分組在一個通用的“父”tasks
部分下,如下所示:
tasks.configure {
// here we configure the Project.taskContainer property.
println " type of current object beeing configured: " it.class.name
// => org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated
create("eagerTask") {
// config
}
register("lazyTask") {
// config
}
}
這會起作用,但不清楚為什么您認為這將有助于處理“通用約定”,也許您可??以提供有關此期望的更多詳細資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521316.html
標籤:毕业典礼
上一篇:Kotlin1.7依賴決議