我已经创建了一个这样的自定义Gradle插件,
DummyPlugin.java
public class DummyPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getTasks().create("dummy", DummyTask.class);
project.getExtensions().create("dummy", DummyExtension.class);
}
}
DummyTask.java
public class DummyTask extends Test {
@TaskAction
public void dummy() {
Project project = getProject();
DummyExtension extension = project.getExtensions().findByType(DummyExtension.class);
System.out.println("Env of dummy is " + extension.getEnv());
}
}
DummyExtension.java
public class DummyExtension {
private String env;
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
}
现在,我为不同的环境创建了三个任务,如下所示:
apply plugin: 'dummy'
task dummyCI(type: DummyTask) {
dummy {
env = 'ci'
}
}
task dummyDev(type: DummyTask) {
dummy {
env = 'dev'
}
}
task dummyTest(type: DummyTask) {
dummy {
env = 'test'
}
}
但是,在运行./gradlew dummyCI
时,我没有获得Env of dummy is ci
,而是获得Env of dummy is test
。同样适用于./gradlew dummyDev
。
如何解决此问题?感谢。
答案 0 :(得分:2)
您要在始终运行的配置阶段设置扩展属性。所以每次调用都会覆盖前一次。要在执行阶段将其设置,请使用doFirst { ... }
块。例如:
task dummyCI(type: DummyTask) {
doFirst {
dummy {
env = 'ci'
}
}
}
或许更好的解决方案是一起摆脱扩展对象,而是将env
属性(输入?)添加到DummyTask