`tasks.named(‘test’)` 与 `test` 之间的区别是:

huangapple go评论61阅读模式
英文:

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

特别是这部分,它解释了你两个示例之间的区别(在你的情况下,someTasktest):

要注意隐藏的急切任务实现。有很多种方式可以急切地配置任务。例如,使用任务名称和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 )

huangapple
  • 本文由 发表于 2023年6月29日 02:45:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定