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

How to get System.getproperty value .java file in build.gradle

我正在尝试将参数从命令行传递给 java class 但无法获取值

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"));
    }
}

收到的输出是 null

我正在通过命令行传递参数:

./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