使用maven,我可以创建一个项目,使用其依赖项设置我的pom,使用main方法编写一个类,然后运行它类型:
mvn compile exec:java -Dexec.mainClass=thornydev.App
这样做的等价物是什么?
我可以gradle build
为我构建一个jar文件,但是如果主类对其他jar有任何依赖,那么只运行jar就不会在没有设置类路径的情况下工作。 gradle java插件可以运行应用程序并为我设置类路径吗?
我正在寻找一种简单的一次性使用命令行解决方案,而不是IDE集成(我知道如何做到这一点)。
答案 0 :(得分:31)
最简单的解决方案是使用Application Plugin,其中包括run
任务。要使主类可以从命令行进行配置,您必须将mainClassName
设置为某个系统(或项目)属性的值,然后从命令行传递该属性:
apply plugin: "application"
mainClassName = System.getProperty("mainClass")
现在,您可以使用gradle run -DmainClass=thornydev.App
运行应用程序。
答案 1 :(得分:0)
我需要在构建过程中运行Java程序,并且应用程序插件带来了太多的包袱。
我使用应用程序插件进行了fidde,但最后我使用了更少“侵入性”JavaExec plugin。
我在MyObfuscator.class
中有一个类文件build.outputDirectory
,在我有这样的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来运行参数化构建。
答案 2 :(得分:0)
如果我的插件是:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
什么是 gradle 中的等价物?