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

19,194

Solution 1

try

@Bean
public SomeService getSomeService(@Value("${property.key}") String key) throws IOException {
    return new SomeService(key);
}

Solution 2

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

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

Solution 3

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);
    }
}

Solution 4

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"));
}
Share:
19,194
Taras Velykyy
Author by

Taras Velykyy

Updated on June 04, 2022

Comments

  • Taras Velykyy
    Taras Velykyy almost 2 years

    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?