在gradle中,可以自定义一些任务,并且可以把任务指定到所有的子工程或者具体某个工程。但是,如果在所有子工程中都定义了某个任务,我们又要在某个工程中忽略该任务,怎么办?本文将会介绍两种解决方法。
演示项目中的父子工程的目录结构
gradle-project
----build.gradle
----springboot
--------build.gradle
----springboot1
--------build.gradle
父工程中的build.gradle中部分关键代码如下,我们给所有的子工程(这里指springboot/springboot1)定义了一个display任务,当运行父工程的display任务的时候,两个子工程springboot/springboot1都会调用display任务,显示各自的工程名
subprojects {
task display() {
doLast {
println project.name
}
}
}
现在,我们想只在springboot1子工程调用display任务。
方法1:
在springboot1子工程的build.gradle中加入
display.enabled=false
缺点是,如果有多个子工程,需要每个build.gradle都加入该代码
方法2:
在父工程中的build.gradle的subprojects节点中加入,意思是当工程名字不为springboot1才执行该display任务
tasks.findAll { task ->
if (task.name == display.name) {
task.onlyIf {
return ('springboot1' != project.name)
}
}
}