Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: get command line argument within @Bean annotated method

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?

like image 558
Taras Velykyy Avatar asked Sep 01 '16 11:09

Taras Velykyy


People also ask

What is @bean annotation in spring boot?

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.

What is annotation @SpringBootApplication?

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.

What are @bean in spring?

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.


1 Answers

 @Bean
 public SomeService getSomeService(
   @Value("${cmdLineArgument}") String argumentValue) {
     return new SomeService(argumentValue);
 }

To execute use java -jar myCode.jar --cmdLineArgument=helloWorldValue

like image 108
Will Humphreys Avatar answered Oct 13 '22 03:10

Will Humphreys