vandit.thakkar
vandit.thakkar

Reputation: 121

Override application property value in Spring from command line argument

We know that we can externalize configuration by @Value annotation like following in Spring boot project.

@Value("${max.routes}")
private int maxRoutes;

In the case, where we give default value in annotation argument itself, the following way,

@Value("${max.routes:10}")
private int maxRoutes;

can we override the value, by passing VM argument, while starting this app?

For example, -Dmax.routes=20. Will it override the value?

Upvotes: 2

Views: 12429

Answers (2)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22506

Take a look at the Externalized Configuration section of Spring boot's documentation:

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments.

It has a very strict rules regarding the precedence of the configuration source:

1 . Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
2 . @TestPropertySource annotations on your tests.
3 . @SpringBootTest#properties annotation attribute on your tests.
4 . Command line arguments.
5 . Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
6 . ServletConfig init parameters.
7 . ServletContext init parameters.
8 . JNDI attributes from java:comp/env.
9 . Java System properties (System.getProperties()).
10. OS environment variables.
11. A RandomValuePropertySource that has properties only in random.*.
12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
14. Application properties outside of your packaged jar (application.properties and YAML variants).
15. Application properties packaged inside your jar (application.properties and YAML variants).
16. @PropertySource annotations on your @Configuration classes.
17. Default properties (specified by setting SpringApplication.setDefaultProperties).

e.g. properties defined in application.propertis will be overridden by OS env variables, Java system properties will override them, and basically Command line arguments will override everything when you're not running tests.

Upvotes: 1

Stefan Ferstl
Stefan Ferstl

Reputation: 5255

Yes, system properties and command line arguments will override these property values.

If you run your application like this...

public static void main(String[] args) {
  SpringApplication.run(MyApplication.class, args);
}

... you cann override your property either with -Dmax.routes=20 or even with an application argument --max.routes=20. Application arguments will have the highes precedence.

Upvotes: 1

Related Questions