5

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?

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

2

try

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

2 Comments

I've never used that annotation and probably I'm wrong but, shouldn't be @Value("#{systemProperties.propertyName}") String key ?
thanks, it works. Correct placeholder is ${property.key}
2

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

Comments

0

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.

1 Comment

Read the value of the property using @Value("myproperty") String key; in java code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.