Reputation: 1801
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?
Upvotes: 5
Views: 25044
Reputation: 16910
You can also inject ApplicationArguments
directly to your bean definition method and access command line arguments from it:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SomeService getSomeService(ApplicationArguments arguments) throws IOException {
String commandLineArgument = arguments.getSourceArgs()[0]; //access the arguments, perform the validation
return new SomeService(commandLineArgument);
}
}
Upvotes: 6
Reputation: 5004
try
@Bean
public SomeService getSomeService(@Value("${property.key}") String key) throws IOException {
return new SomeService(key);
}
Upvotes: 2
Reputation: 2791
@Bean
public SomeService getSomeService(
@Value("${cmdLineArgument}") String argumentValue) {
return new SomeService(argumentValue);
}
To execute use java -jar myCode.jar --cmdLineArgument=helloWorldValue
Upvotes: 15
Reputation: 161
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.
Upvotes: 0
Reputation: 2340
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"));
}
Upvotes: 2