Gradle Exec:为什么它不在配置阶段运行?

cha*_*ny1 5 exec mkdir gradle

这是我的:

构建.gradle

task makeDirectoryStructure(type:Exec){

    description 'Creates directory structure .'

    commandLine 'mkdir'
    args '-p' ,'top_dir/sub_dir_1/sub_dir_2'
    println "This line is printed in configuration phase."
}
Run Code Online (Sandbox Code Playgroud)

现在,由于我还没有使用“ << ”或<“ doFirst/doLast ”,我希望mkdir在配置阶段即在编译构建脚本时执行。例如,如果我这样做

$gradle tasks
Run Code Online (Sandbox Code Playgroud)

我希望 mkdir 在配置阶段运行,即我的目录结构应该形成但没有发生。

但是我得到这个输出:

yogeshwardancharan@yogeshwardancharan-Lenovo-G570:~/android_learning_resources/gradle_resources/ud867/1.01-Exercise-RunYourFirstTask$ gradle tasks
This line is printed in configuration phase.
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
components - Displays the components produced by root project '1.01-Exercise-RunYourFirstTask'. [incubating]
dependencies - Displays all dependencies declared in root project '1.01-Exercise-RunYourFirstTask'.
dependencyInsight - Displays the insight into a specific dependency in root project '1.01-Exercise-RunYourFirstTask'.
help - Displays a help message.
model - Displays the configuration model of root project '1.01-Exercise-RunYourFirstTask'. [incubating]
projects - Displays the sub-projects of root project '1.01-Exercise-RunYourFirstTask'.
properties - Displays the properties of root project '1.01-Exercise-RunYourFirstTask'.
tasks - Displays the tasks runnable from root project '1.01-Exercise-RunYourFirstTask'.

Other tasks
-----------
makeDirectoryStructure - Creates directory structure .
Run Code Online (Sandbox Code Playgroud)

现在,在这一行的上面输出打印中

此行在配置阶段打印。

确认任务确实在配置阶段被处理。

而且,当我发出命令时

$gradle makeDirectoryStructure
Run Code Online (Sandbox Code Playgroud)

以上两行都打印出来,目录结构也形成了。

所以,最后的问题是为什么我的mkdir不在配置阶段运行,或者我是一些非常常见的概念。

Opa*_*pal 5

请看一下AbstractExecTask从哪个Exec继承。正如您所看到的,有很多 getter 和 setter。配置时发生的事情是仅设置这些字段的值,而不是运行它们。exec()仅当调用注释的方法时才会使用所有设置的属性@TaskAction- 这在运行时发生。为什么println有效?它只是一个被调用的方法,与上面提到的 setter 的方式完全相同 -println只是具有可见的效果,而 setter 只是更改稍后使用的属性。

每个任务都有其动作。不同之处在于,在配置阶段仅配置任务,并且在执行任务操作时使用此配置。