0

What is the best way of passing parameters into TestConfig.class below? I cannot figure it out.

Calling method like this from command line:

com.test.app.Launcher --param.1=test1 --param.2=test2

Main method code is:

public static void main(String[] args) throws Throwable {
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
   // ...
}

Later on in the program, I want to access the parameters as follows...

public class TestConfig {
   
   // how do I access the values in clps here? is this right??

   @Autowired
   private Environment env;

   private final String PARAM_1 = env.getProperty("param.1");
   private final String PARAM_2 = env.getProperty("param.2");

}
halfer
  • 19,824
  • 17
  • 99
  • 186
methuselah
  • 12,766
  • 47
  • 165
  • 315
  • 1
    Is there a reason why you don't just use the normal property handling in properties, yaml, environment, command line ? – Marged Jan 08 '18 at 20:15
  • It's because I am calling the app from an external source and the parameters passed can vary – methuselah Jan 08 '18 at 20:25
  • Parameter keys or values ? Boot supports command line passed parameters too: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html – Marged Jan 08 '18 at 20:36
  • `By default SpringApplication will convert any command line option arguments (starting with ‘--’, e.g. --server.port=9000) to a property and add it to the Spring Environment. As mentioned above, command line properties always take precedence over other property sources.` ... this is what I mean. How would I access it from `TestConfig.class` if its a property in the Spring Environment? – methuselah Jan 08 '18 at 20:40
  • Like here: https://stackoverflow.com/questions/39047333/spring-boot-value-properties – Marged Jan 08 '18 at 20:44
  • But isn't the example reading from a `application.properties` file, I want to read the command line properties – methuselah Jan 08 '18 at 20:49
  • I've updated the question... please let me know if its correct – methuselah Jan 08 '18 at 21:06
  • Have a look at the answer and see how @Value is used. Boot treats .properties and command line parameters the same way, what you are looking for is how to specify where to put the read values – Marged Jan 09 '18 at 04:10

1 Answers1

0

Like can be seen on several answers here on stack overflow you can use @Value to "import" values:

@Value("${my.param}")
private String param;

These parameters can come from several sources, command line parameters in the shape of -D and real command line parameters are one. See here for a list of supported sources.

Marged
  • 10,577
  • 10
  • 57
  • 99