groovy - 何时在 Gradle 任务中使用 "<<"

标签 groovy gradle

有时我会看到:

task hey << {
    println "Hello, Gradle!"
}

我看到的其他时候:

task hey {
    println "Hello, Gradle!"
}

什么时候使用“<<”,什么时候不使用(以及为什么)?

最佳答案

<<doLast 的简写。您问题中的任务不等价。

这个任务:

task hey << {
    println "Hello, Gradle!"
}

相当于这个任务:

task hey {
    doLast {
        println "Hello, Gradle!"
    }
}

无论您是否正在运行该特定任务,每次执行构建脚本时都会执行第二个示例中的代码。例如,如果您有以下任务然后运行 ​​gradle goodbye ,您将看到“Hello, World!”和“再见,世界!”即使您只是执行“再见”任务:

task hello {
    println "Hello, world!"
}

task goodbye {
    println "Goodbye, world!"
}

结果:

$ gradle goodbye
Hello, world!
Goodbye, world!
:goodbye UP-TO-DATE

但是,如果您将任务定义更新为使用 <<doLast(例如 task hello << {} ),您将只能看到您执行的任务中的 println

Adam Murdoch 描述了任务中的代码何时将在 this post 中执行。我在这里引用了一些相关信息:

There are 2 different points in time when code related to a task is executed: The first is configuration time, which is when the build script executes. The idea is that at this time you configure the task, so that it does the right thing at the other point in time, namely, execution time. Execution time is the point in time where the task does its actual work, and happens only if the task is selected for execution, and after its dependencies have executed.

Each task has a sequence of actions, which are run in the order specified when the task executes. An action is simply a closure or an Action implementation. The doFirst() method configures the task to add an action at the start of the sequence. The doLast() and << methods configure the task to add an action at the end of the sequence.

关于groovy - 何时在 Gradle 任务中使用 "<<",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071462/

相关文章:

java - 在 Python 和 Groovy 之间传输简单对象

android - 如何从命令行创建 Android 项目

java - 基于spring.profiles.active动态编译依赖

android - Gradle 在浪费我的时间

android - Android Studio中缺少org.mozilla.javascript.Scriptable

grails - 从 "View"发送数据到 "Controller"

Grails:理解 groovy DomainClass.properties

eclipse - Eclipse 中的参数化 Groovy JUnit 测试用例

android - gradle kotlin-dsl 将 android {} 移动到根项目 build.gradle.kts 中的子项目 {}

jenkins - 脚本不允许使用 staticMethod java.time.Instant parse java.lang.CharSequence