【发布时间】:2014-07-04 12:56:23
【问题描述】:
我正在尝试通过 Gradle 运行命令行 Java 应用程序,作为快速集成测试的一部分。我正在从 Maven 移植我的构建脚本,这可以通过 exec-maven-plugin 轻松完成。我的两大要求是:
- 能够将系统属性传递给可执行的 Java 代码
- 能够将命令行参数传递给可执行的 Java 代码
请注意,我不是要在构建脚本中读取这些属性,而是要在脚本构建和执行的 Java 程序中读取它们。
我发现了另外两篇关于通过 Gradle 执行 Java 程序的 SO 帖子:one with an answer that advocates using apply plugin: "application" in the build file and gradle run at the command line 和 another with answers advocating that approach as well as using task execute(type:JavaExec) in the build file and gradle execute at the command line。这两种方法我都试过了,都没有成功。
我有两个问题:
(1) 我无法让 Java 可执行文件读取系统属性
我是否这样做:
build.gradle:
apply plugin: 'application'
mainClassName = "com.mycompany.MyMain"
命令行:
gradle run -Dmyproperty=myvalue
或者这个:
build.gradle:
task execute (type:JavaExec) {
main = "com.mycompany.MyMain"
classpath = sourceSets.main.runtimeClasspath
}
命令行:
gradle execute -Dmyproperty=myvalue
在任何一种情况下,myproperty 都无法通过。从MyMain.main (...) 开始运行的代码将myproperty 系统属性读取为空/缺失。
(2) 我无法传递命令行参数
这可能与第一个问题有关。例如,在exec-maven-plugin 中,命令行参数本身是通过系统属性传入的。 Gradle 就是这种情况,还是有其他方法可以传递命令行参数?
如何通过这些变量?还有,是apply plugin: 'application'还是task execute (type:JavaExec)更好?
【问题讨论】:
-
systemProperties = System.properties as Map