如何在build.gradle中获取System.getproperty值.java文件



我试图将一个参数从命令行传递到java类,但无法获得值

build.gradle包含

plugins {
id 'java'
}
group 'test'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
}
}
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
options.deprecation = true
}
test {
systemProperty "host", System.getProperty("host")
systemProperty "port", System.getProperty("port")
}
dependencies {
testImplementation(platform('org.junit:junit-bom:5.7.1'))
testImplementation('org.junit.jupiter:junit-jupiter')
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.13.3'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.3'
compile fileTree(include: ['*.jar'], dir: 'lib')
implementation group: 'org.json', name: 'json', version: '20210307'
}

src/main/test/test.java

public class test {
public static void main(String[] args) {
System.out.println("Recieved ip is:"+System.getProperty("host"));
System.out.println("Recieved port is:"+System.getProperty("port"));
}
}

接收输出为

我通过命令行传递参数:

./gradlew clean build test -Dhost=127.0.0.1 -Dport=4433

如何获得这些值

提前感谢

将其添加到您的build.gradle文件中

task serverArgs(type: JavaExec) {
group = "Execution"
description = "Run the main class with ServerArgs"
classpath = sourceSets.main.runtimeClasspath
main = "you main class path" //test.test
systemProperty "host", System.getProperty("host")
systemProperty "port", System.getProperty("port")
}

并像这样执行

./gradlew clean serverArgs build test -Dhost=127.0.0.1 -Dport=4433

输出为:

接收的ip为:127.0.0.1

接收端口为:4433

最新更新