Spring - Accessing application arguments with CommandLinePropertySource

[Updated: Apr 22, 2017, Created: Apr 22, 2017]

CommandLinePropertySource is PropertySource subclass which is backed by command line arguments passed to a Java Application.

java.lang.ObjectObjectorg.springframework.core.env.PropertySourcePropertySourceorg.springframework.core.env.EnumerablePropertySourceEnumerablePropertySourceorg.springframework.core.env.CommandLinePropertySourceCommandLinePropertySourceorg.springframework.core.env.SimpleCommandLinePropertySourceSimpleCommandLinePropertySourceorg.springframework.core.env.JOptCommandLinePropertySourceJOptCommandLinePropertySourceLogicBig

In this tutorial, we will see the examples of using the two CommandLinePropertySource implementations: SimpleCommandLinePropertySource and JOptCommandLinePropertySource.

Using SimpleCommandLinePropertySource without Spring context

public class CmdSourceExample1 {

  public static void main(String[] args) {
      SimpleCommandLinePropertySource ps = new SimpleCommandLinePropertySource(args);
      Arrays.stream(ps.getPropertyNames()).forEach(s ->
              System.out.printf("%s => %s%n", s, ps.getProperty(s)));
  }
}
mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample1" -Dexec.args="--myProp=testval1 --myProp2=testVal2"

Output

D:\example-projects\spring\command-line-property-source-example>mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample1" -Dexec.args="--myProp=testval1 --myProp2=testVal2"
myProp => testval1
myProp2 => testVal2

We can also use run configuration of an IDE to pass args, here we are demonstrating our examples with maven.

Using SimpleCommandLinePropertySource with Spring context

@Configuration
public class CmdSourceExample2 {

    @Bean
    public MyBean myBean1(){
        return new MyBean();
    }
    public static void main(String[] args) {

        PropertySource theSource = new SimpleCommandLinePropertySource(args);

        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(CmdSourceExample2.class);

        context.getEnvironment().getPropertySources().addFirst(theSource);

        MyBean bean = context.getBean(MyBean.class);
        bean.doSomething();
    }


    public class MyBean {
        @Autowired
        private Environment environment;

        public void doSomething() {
            String value = environment.getProperty("myProp");
            System.out.println("the value of myProp: " + value);
        }
    }
}
mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample2" -Dexec.args="--myProp=testval1 --myProp2=testVal2"

Output

D:\example-projects\spring\command-line-property-source-example>mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample2" -Dexec.args="--myProp=testval1 --myProp2=testVal2"
the value of myProp: testval1
May 01, 2017 3:21:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5cdf6949: startup date [Mon May 01 15:21:10 CDT 2017]; root of context hierarchy

Using SimpleCommandLinePropertySource and @Value annotation

@Configuration
public class CmdSourceExample3 {

    @Bean
    public MyBean myBean(){
        return new MyBean();
    }

    public static void main(String[] args) {

        PropertySource theSource = new SimpleCommandLinePropertySource(args);

        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext();

        context.getEnvironment().getPropertySources().addFirst(theSource);

        context.register(CmdSourceExample3.class);
        context.refresh();

        MyBean bean = context.getBean(MyBean.class);
        bean.doSomething();
    }

    public class MyBean {
        @Value("${myProp}")
        private String myPropValue;

        public void doSomething() {
            System.out.println("the value of myProp: " + myPropValue);
        }
    }
}
mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample3" -Dexec.args="--myProp=testval1 --myProp2=testVal2"

Output

D:\example-projects\spring\command-line-property-source-example>mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample3" -Dexec.args="--myProp=testval1 --myProp2=testVal2"
the value of myProp: testval1
May 01, 2017 3:21:13 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5eee962c: startup date [Mon May 01 15:21:13 CDT 2017]; root of context hierarchy

Using JOptCommandLinePropertySource

JOptCommandLinePropertySource is backed by OptionSet (part of a third party library, JOpt Simple, which supports various unix style options/arguments). To see what it can do, let's see a simple example first (we have already included maven dependency of JOpt simple in project browser below):

public class CmdSourceExample4 {

    public static void main(String[] args) {
        OptionParser parser = new OptionParser();
        parser.accepts("myProp").withRequiredArg();
        OptionSet options = parser.parse(args);

        boolean myProp = options.hasArgument("myProp");
        System.out.println(myProp);
        Object myProp1 = options.valueOf("myProp");
        System.out.println(myProp1);
    }
}
mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample4" -Dexec.args="-myProp testval1"

Output

D:\example-projects\spring\command-line-property-source-example>mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample4" -Dexec.args="-myProp testval1"
true
testval1

Let's use it with JOptCommandLinePropertySource:

@Configuration
public class CmdSourceExample5 {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) {
        OptionParser parser = new OptionParser();
        parser.accepts("myProp").withRequiredArg();
        OptionSet options = parser.parse(args);

        PropertySource ps = new JOptCommandLinePropertySource(options);

        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext();

        context.getEnvironment().getPropertySources().addFirst(ps);

        context.register(CmdSourceExample5.class);
        context.refresh();

        MyBean bean = context.getBean(MyBean.class);
        bean.doSomething();
    }

    public class MyBean {
        @Value("${myProp}")
        private String myPropValue;

        public void doSomething() {
            System.out.println("the value of myProp: " + myPropValue);
        }
    }
}
mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample5" -Dexec.args="-myProp testval1"

Output

D:\example-projects\spring\command-line-property-source-example>mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.CmdSourceExample5" -Dexec.args="-myProp testval1"
the value of myProp: testval1
May 01, 2017 3:21:18 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@26b3cbab: startup date [Mon May 01 15:21:18 CDT 2017]; root of context hierarchy

Example Project

Dependencies and Technologies Used :

  • spring-context 4.3.8.RELEASE: Spring Context.
  • jopt-simple 5.0.3: A Java library for parsing command line options.
  • JDK 1.8
  • Maven 3.3.9

Spring Command Line Args Examples Select All Download
  • command-line-property-source-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also