Gradle 运行Java Main 类
文章来源
翻译自 Run a Java main Method Using Gradle,尊重原创
简介
在这个教程中,我们将探索使用Gradle
执行Java Main
的不同的方法。
Java Main
打印到控制台
public class MainClass {
public static void main(String[] args) {
System.out.println("Goodbye cruel world ...");
}
}
使用application
插件运行
这个插件是一个核心的Gradle
插件,他定义了一系列线程的任务,帮助我们打包盒分发应用程序。
build.gradle
plugins {
id "application"
}
apply plugin : "java"
ext {
javaMainClass = "com.baeldung.gradle.exec.MainClass"
}
application {
mainClassName = javaMainClass
}
该插件会自动生成一个名为run
的任务,主需要将其指向主类即可
运行命令
~/work/baeldung/tutorials/gradle-java-exec> ./gradlew run
> Task :run
Goodbye cruel world ...
BUILD SUCCESSFUL in 531ms
2 actionable tasks: 1 executed, 1 up-to-date
利用 JavaExec 任务执行
利用 JavaExec
任务类型运行主类
task runWithJavaExec(type: JavaExec) {
group = "Execution"
description = "Run the main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
main = javaMainClass
}
运行命令
~/work/baeldung/tutorials/gradle-java-exec> ./gradlew runWithJavaExec
> Task :runWithJavaExec
Goodbye cruel world ...
BUILD SUCCESSFUL in 526ms
2 actionable tasks: 1 executed, 1 up-to-date
利用 Exec
任务
从编译构建输出运行
任务
task runWithExec(type: Exec) {
dependsOn build
group = "Execution"
description = "Run the main class with ExecTask"
commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass
}
运行命令
~/work/baeldung/tutorials/gradle-java-exec> ./gradlew runWithExec
> Task :runWithExec
Goodbye cruel world ...
BUILD SUCCESSFUL in 666ms
6 actionable tasks: 6 executed
编译成.class
运行
任务
task runWithExecJarOnClassPath(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the mainClass from the output jar in classpath with ExecTask"
commandLine "java", "-classpath", jar.archiveFile.get(), javaMainClass
}
运行
~/work/baeldung/tutorials/gradle-java-exec> ./gradlew runWithExecJarOnClassPath
> Task :runWithExecJarOnClassPath
Goodbye cruel world ...
BUILD SUCCESSFUL in 555ms
3 actionable tasks: 3 executed
编译成 .jar
运行
文件
jar {
manifest {
attributes(
"Main-Class": javaMainClass
)
}
}
task runWithExecJarExecutable(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the output executable jar with ExecTask"
commandLine "java", "-jar", jar.archiveFile.get()
}
运行
~/work/baeldung/tutorials/gradle-java-exec> ./gradlew runWithExecJarExecutable
> Task :runWithExecJarExecutable
Goodbye cruel world ...
BUILD SUCCESSFUL in 572ms
3 actionable tasks: 3 executed
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验