1

我创建了一个这样的自定义 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);
    }
}

虚拟任务.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 ciEnv of dummy is test./gradlew dummyDev

我该如何解决这个问题?谢谢。

4

1 回答 1

2

您在始终运行的配置阶段设置扩展属性。所以每次调用都会覆盖前一次。要在执行阶段设置它,请使用doFirst { ... }块。例如:

task dummyCI(type: DummyTask) {
    doFirst {
        dummy {
            env = 'ci'
        }
    }
}

或者也许更好的解决方案是一起摆脱扩展对象,而是将env属性(输入?)添加到DummyTask

于 2016-11-04T16:25:19.683 回答