有简单的 Eclipse 插件来运行 Gradle,只需使用命令行方式启动 gradle。
maven编译和运行的gradle模拟是什么
mvn compile exec:java -Dexec.mainClass=example.Example
这样任何带有
gradle.build
的项目都可以运行。
更新:有类似的问题用于运行Java应用程序的maven exec插件的gradle等效项是什么?之前问过,但解决方案建议更改每个项目
build.gradle
package runclass;
public class RunClass {
public static void main(String[] args) {
System.out.println("app is running!");
}
}
然后执行
gradle run -DmainClass=runclass.RunClass
:run FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> No main class specified
在 gradle 中没有与
mvn exec:java
直接等效的东西,您需要应用 application
插件或有 JavaExec
任务。
application
插件激活插件:
plugins {
id 'application'
...
}
配置如下:
application {
mainClassName = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "NULL"
}
在命令行中写入
$ gradle -PmainClass=Boo run
JavaExec
任务定义一个任务,比如说
execute
:
task execute(type:JavaExec) {
main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
classpath = sourceSets.main.runtimeClasspath
}
要运行,请写
gradle -PmainClass=Boo execute
。你得到
$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!
mainClass
是在命令行动态传入的属性。 classpath
即将开始最新的课程。
如果您不传入
mainClass
属性,则两种方法都会按预期失败。
$ gradle execute
FAILURE: Build failed with an exception.
* Where:
Build file 'xxxx/build.gradle' line: 4
* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.
您只需要使用Gradle应用程序插件:
apply plugin:'application'
mainClass = "org.gradle.sample.Main"
然后简单地
gradle run
。
正如 Teresa 指出的,您还可以将
mainClass
配置为系统属性并使用命令行参数运行。
扩展第一个零的答案,我猜你想要一些可以运行
gradle build
而不会出现错误的东西。
gradle build
和gradle -PmainClass=foo runApp
都可以使用:
task runApp(type:JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}
您设置默认主类的位置。
你可以参数化它并传递 gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}
如果使用 Kotlin DSL 和 gradle8.5(或者甚至更新的版本),似乎我需要这样写:
// If you use "application" plugin
// run as: ./gradlew run
application {
mainClass.set("org.example.Main")
}
// Or, if you use the "java" plugin, this defines a custom task called "runMe" via the JavaExec task type, and it does the same thing as above
// run as: ./gradlew runMe
tasks.register<JavaExec>("runMe") {
classpath = sourceSets["main"].runtimeClasspath
mainClass = "org.example.Main"
}
有关 JavaExec 的更多信息。 API 文档中的 groovy 示例不是很有帮助...