What is the gradle equivalent of maven's exec plugin for running Java apps?
The easiest solution is to use the Application Plugin, which among other things provides a run
task. To make the main class configurable from the command line, you'll have to set mainClassName
to the value of some system (or project) property, and then pass that property from the command line:
apply plugin: "application"
mainClassName = System.getProperty("mainClass")
Now you can run the application with gradle run -DmainClass=thornydev.App
.
I needed to run a Java program as part of the build process, and the application plugin came with too much baggage.
I did fidde with the application plugin, but in the end I used the much less "invasive" JavaExec plugin.
I have a class file MyObfuscator.class
in the build.outputDirectory
and before I had a pom.xml
like this, which ran code obfuscation in the build directory with two parameters:
<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>
I boiled it down to this thing in 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"
}
If you need parameterized execution like in the Maven example above, then add a few lines to the task:
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"]
}
Then depend the assemble
task on obfuscate
(put this line anywhere below the obfuscate
task definition):
assemble.dependsOn obfuscate
Or let the (earlier) jar
task depend on it. See the graph at the bottom of this docs section here for more ideas on where to inject this.
You can then call gradle like gradle build -PPARAM1=HELLO
to run a parameterized build.