I'm building a Spring Boot application and need to read command line argument within method annotated with @Bean. See sample code:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(commandLineArgument);
}
}
How can I solve my issue?
try
@Bean
public SomeService getSomeService(@Value("${property.key}") String key) throws IOException {
return new SomeService(key);
}
@Bean
public SomeService getSomeService(
@Value("${cmdLineArgument}") String argumentValue) {
return new SomeService(argumentValue);
}
To execute use java -jar myCode.jar --cmdLineArgument=helloWorldValue
If you run your app like this:
$ java -jar -Dmyproperty=blabla myapp.jar
or
$ gradle bootRun -Dmyproperty=blabla
Then you can access this way:
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(System.getProperty("myproperty"));
}
you can run your app like this:
$ java -server -Dmyproperty=blabla -jar myapp.jar
and can access the value of this system property in the code.