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?
Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.
Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.
Bean Definition In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
@Bean
public SomeService getSomeService(
@Value("${cmdLineArgument}") String argumentValue) {
return new SomeService(argumentValue);
}
To execute use java -jar myCode.jar --cmdLineArgument=helloWorldValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With