英文:
Difference between `tasks.named('test')` and `test`
问题
我注意到 https://start.spring.io 现在使用以下代码:
tasks.named('test') {
useJUnitPlatform()
}
而之前是这样的:
test {
useJUnitPlatform()
}
我想知道为什么有这个变化?第二个看起来在IDE上更清晰。
这两者都是Groovy Gradle,不是Kotlin。
英文:
I noticed that https://start.spring.io now uses
tasks.named('test') {
useJUnitPlatform()
}
When it used to be
test {
useJUnitPlatform()
}
I was wondering why the change? The second one seems cleaner even on the IDE.
These are both groovy Gradle no Kotlin
答案1
得分: 4
这个变更是为了懒加载地声明任务,详见Gradle页面描述的“配置避免”原则:https://docs.gradle.org/current/userguide/task_configuration_avoidance.html
特别是这部分,它解释了你两个示例之间的区别(在你的情况下,someTask
是test
):
要注意隐藏的急切任务实现。有很多种方式可以急切地配置任务。例如,使用任务名称和DSL块配置任务将导致任务在使用Groovy DSL时立即创建。
// 给定一个懒加载创建的任务
tasks.register("someTask")
// 一段时间后,使用DSL块配置任务
someTask {
// 这将导致任务被创建并立即执行此配置
}
相反,使用named()方法获取任务的引用并进行配置:
tasks.named("someTask") {
// 在这里进行配置
}
(相关提交Spring initializr项目:https://github.com/spring-io/initializr/commit/27fc9d40672496c93742f562b13544d9a27cd484)
英文:
This change has been made to declare tasks lazily, see this Gradle page describing the "Configure avoidance" principles : https://docs.gradle.org/current/userguide/task_configuration_avoidance.html
Especialy this part which explains the difference between your two examples ( someTask
is test
in your case):
> Beware of the hidden eager task realization. There are many ways that a task can be configured eagerly. For example, configuring a task using the task name and a DSL block will cause the task to immediately be created when using the Groovy DSL
> // Given a task lazily created with
> tasks.register("someTask")
>
> // Some time later, the task is configured using a DSL block
> someTask {
> // This causes the task to be created and this configuration to be executed immediately
> }
> Instead use the named() method to acquire a reference to the task and configure it:
> tasks.named("someTask") {
>
> }
( related commit Spring initializr project : https://github.com/spring-io/initializr/commit/27fc9d40672496c93742f562b13544d9a27cd484 )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论