我需要在构建过程中运行一个 Java 程序,而应用程序插件带来了太多的包袱。
我确实不喜欢应用程序插件,但最后我使用了“侵入性”要小得多的JavaExec plugin。
我在build.outputDirectory 中有一个类文件MyObfuscator.class,在我有一个像这样的pom.xml 之前,它使用两个参数在构建目录中运行代码混淆:
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>obfuscate</id>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>java</executable>
<workingDirectory>${project.build.outputDirectory}</workingDirectory>
<arguments>
<argument>-Djava.library.path=.</argument>
<argument>-classpath</argument>
<argument>${project.build.outputDirectory}:lib.jar</argument>
<argument>MyObfuscator</argument>
<argument>HELLO</argument>
<argument>GOODBYE</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
</project>
我在 Gradle 中把它归结为这个东西:
apply plugin: "java"
// ...
task obfuscate(type: JavaExec) {
// Make sure it runs after compilation and resources.
// Skip this if that's not a requirement.
dependsOn classes
// run in the buildDir (this requirement was what
// made a simple "doLast" infeasible)
workingDir = file(buildDir)
classpath = files([
"${buildDir}/classes",
"${buildDir}/resources/main/lib.jar"
])
main = "MyObfuscator"
}
如果您需要像上面的 Maven 示例中那样参数化执行,则在任务中添加几行:
task obfuscate(type: JavaExec) {
// ... (as above)
// Set PARAM1 to a default value when it's not
// defined on the command line
if(!project.hasProperty("PARAM1")) {
ext.PARAM1 = "HELLO"
}
// PARAM1 is dynamic and PARAM2 is static, always "GOODBYE"
args = [PARAM1, "GOODBYE"]
}
然后将assemble 任务依赖于obfuscate(将此行放在obfuscate 任务定义下方的任意位置):
assemble.dependsOn obfuscate
或者让(之前的)jar 任务依赖它。请参阅this docs section here 底部的图表,了解更多关于在何处注入的想法。
然后您可以像 gradle build -PPARAM1=HELLO 这样调用 gradle 来运行参数化构建。