Taras Velykyy
Taras Velykyy

Reputation: 1801

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?

Upvotes: 5

Views: 25044

Answers (5)

Michał Krzywański
Michał Krzywański

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

rocky
rocky

Reputation: 5004

try

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

Upvotes: 2

Will Humphreys
Will Humphreys

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

Sourabh Kanojiya
Sourabh Kanojiya

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

exoddus
exoddus

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

Related Questions