Monday, September 11, 2017

Passing System Properties and Arguments With Gradle

When using the Gradle application plugin, Gradle spawns a new JVM on the fly, and does not pass the System Properties or Command-line arguments to the new Java process. This post explains how to pass the System properties and command-line arguments when using Gradle application plugin. There are multiple ways to pass the System properties or arguments to the Application

Pass all System properties

systemProperties System.getProperties()

Pass specific system property

systemProperty "prop1", System.getProperty("prop1")

Pass a subset of System Properties

In the following example, we only pass system properties that start with "a".
System.properties.each { key,value->
 if (key.startsWith("a")) {
  systemProperty key, value
 }
}

Pass command line arguments

For this you can read the arguments as a Gradle System property and pass on the application in using "args" as shown below.
args System.getProperty("exec.args")

Full Code

Folder Structure

GradleSysPropsExample
│   build.gradle
└───src
    ├───main
    │   └───java
    │       └───com
    │           └───aoj
    │                   GradleSysPropsExample.java
    │
    └───test
        └───java

GradleSysProperExample.java

package com.aoj;

public class GradleSysPropsExample {

  public static void main(String[] args) {

    //System.getProperties().forEach((key, value) -> System.out.println(key + " : " + value));
    
    //System.out.println("System Property prop1 = " + System.getProperty("prop1"));
    System.out.println("System Property aoj-cmd-args = " + System.getProperty("aoj-cmd-args"));
    System.out.println("Command line arguments");
    for(String arg: args) {
      System.out.println(arg);
    }
  }
}

build.gradle

apply plugin:'application'
mainClassName = "com.aoj.GradleSysPropsExample"
applicationName = 'GracleSysPropsExample'
repositories {
    mavenCentral()
}

dependencies {
}

run {    
    // Pass all system properties
   // systemProperties System.getProperties()

    // Pass specific system property
    systemProperty "prop1", System.getProperty("prop1")
    
    
    // Pass argument starting with "a"
    System.properties.each { key,value->
        if (key.startsWith("a")) {
            systemProperty key, value
        }
    }

    // Pass command line arguments
    args System.getProperty("aoj-cmd-args").split(',')
}

To run this example

gradle run -Dprop1=prop1value -Daoj-cmd-args="arg1,arg2"

2 comments:

  1. Thank you! I just needed to pass all system properties to application when running tests and this worked:

    test {
    systemProperties System.getProperties()
    }

    ReplyDelete

Popular Posts