gpt4 book ai didi

java - 通过 Gradle 运行 Java 类时传递系统属性和参数的问题

转载 作者:IT老高 更新时间:2023-10-28 11:49:34 24 4
gpt4 key购买 nike

我正在尝试通过 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 系统属性读取为 null/missing。

(2) 我无法传递命令行参数

这可能与第一个问题有关。例如,在 exec-maven-plugin 中,命令行参数本身是通过系统属性传入的。 Gradle 就是这种情况,还是有其他方法可以传递命令行参数?

如何通过这些变量?另外,使用 apply plugin: 'application' 还是 task execute (type:JavaExec) 更好?

最佳答案

想通了。主要问题是当 Gradle 派生一个新的 Java 进程时,它不会自动将环境变量值传递给新环境。必须通过任务或插件的 systemProperties 属性显式传递这些变量。

另一个问题是理解如何传递命令行参数;这些是通过任务或插件上的 args 属性。与 Maven exec-maven-plugin 一样,它们应该通过另一个系统属性在命令行中传递,作为空格分隔的列表,然后需要 split() 在设置 args 之前,它接受 List 对象。我已将属性命名为 exec.args,这是旧的 Maven 名称。

似乎 javaExec 和应用程序插件方法都是有效的。如果想使用它的一些其他功能(自动组合发行版等),可能会更喜欢应用程序插件方法

以下是解决方案:

JavaExec 方法

命令行:

gradle execute -Dmyvariable=myvalue -Dexec.args="arg1 arg2 arg3"

build.gradle:

task execute (type:JavaExec) {

main = "com.myCompany.MyMain"
classpath = sourceSets.main.runtimeClasspath

/* Can pass all the properties: */
systemProperties System.getProperties()

/* Or just each by name: */
systemProperty "myvariable", System.getProperty("myvariable")

/* Need to split the space-delimited value in the exec.args */
args System.getProperty("exec.args", "").split()
}

应用程序插件方法

命令行:

gradle run -Dmyvariable=myvalue -Dexec.args="arg1 arg2 arg3"

build.gradle:

apply plugin: 'application'
mainClassName = "com.mycompany.MyMain"
run {
/* Can pass all the properties: */
systemProperties System.getProperties()

/* Or just each by name: */
systemProperty "myvariable", System.getProperty("myvariable")

/* Need to split the space-delimited value in the exec.args */
args System.getProperty("exec.args", "").split()
}

关于java - 通过 Gradle 运行 Java 类时传递系统属性和参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com