Gradle的核心是基于依赖的编程语言。你可以使用Gradle定义task和task之间的依赖。Gradle保证每个task根据依赖关系决定的次序执行,并且只执行一次。这些task组成一个有向无环图。Gradle将会在执行task 之前构建这个有向无环图。
构建阶段
一次Gradle构建由三个阶段组成:
初始化
Gradle决定哪些项目将参与这次构建,并为每个项目生成一个Project对象。
配置
在这个阶段,Gradle将根据每个项目的构建脚本配置每个Project对象。
执行
Gradle根据命令行的输入,在配置阶段生成的task集合中,挑选出将被执行的task,并执行它们。
Settings文件
除了构建脚本外,Gradle定义了一个Settings文件。这个文件的默认名是settings.gradle。Settings文件在配置阶段执行。对于多项目构建,settings.gradle定义了将被构建的项目。对于单项目构建,Settings文件是可选的。
下面是一次Gradle构建执行的例子:
Example: Single project build
settings.gradle
println 'This is executed during the initialization phase.'
build.gradle
println 'This is executed during the configuration phase.'
task configured {
println 'This is also executed during the configuration phase.'
}
task test {
doLast {
println 'This is executed during the execution phase.'
}
}
task testBoth {
doFirst {
println 'This is executed first during the execution phase.'
}
doLast {
println 'This is executed last during the execution phase.'
}
println 'This is executed during the configuration phase as well.'
}
Output of gradle test testBoth
> gradle test testBoth
This is executed during the initialization phase.
> Configure project :
This is executed during the configuration phase.
This is also executed during the configuration phase.
This is executed during the configuration phase as well.
> Task :test
This is executed during the execution phase.
> Task :testBoth
This is executed first during the execution phase.
This is executed last during the execution phase.
BUILD SUCCESSFUL in 0s
2 actionable tasks: 2 executed
多项目构建
一次多项目构建是指一次Gradle构建执行的过程中构建超过一个项目。
项目位置
一般来说,多项目可以被组织为一个单根数,树的每个结点代表一个项目。大多数情况下,项目的物理存储位置和在树中的位置是一致的,但这个映射也可以在settings.gradle中进行配置。
基于构建脚本生命周期的响应
在构建脚本中可以接收构建过程中的通知,你可以通过实现一个监听器接口或者提供一个闭包来处理这些通知。比如:
allprojects {
afterEvaluate { project ->
if (project.hasTests) {
println "Adding test task to $project"
project.task('test') {
doLast {
println "Running tests for $project"
}
}
}
}
}