Spring Boot: get command line argument within @Bea

2020-02-11 07:24发布

问题:

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?

回答1:

try

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


回答2:

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

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



回答3:

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


回答4:

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.