Different ways to externalize properties in sprint boot application
Every spring boot project provides way to set properties values through application.properties or application.yml file which are bundled in code. But there are could be requirement to change those properties values while starting app. For example,
- Changing server locations which will be based on environment.
- Increasing timeouts etc.
Spring boot provides ways to override default properties.
Having different profile
We can have properties defined for every environment. Defining properties files for every environment helps to do that.
So if we want to have properties defined for test env, we can define application-test.yml.
Starting app with test profile will make sure that properties are loaded from application-test.yml.
Command to start application in test profile.
java -jar -Dspring.profiles.active=test <yourapp.jar>
Passing config file while starting application
SpringApplication
will load properties from application.properties
or yml files in the following locations and add them to the Spring Environment
:
- A
/config
subdir of the current directory. - The current directory
- A classpath
/config
package - The classpath root
The list is ordered by precedence (locations higher in the list override lower items).
Apart than this we can pass properties file through command line arguments as well which will take higher precedence than above mentioned options.
java -jar <yourapp.jar> — spring.config.additional-location=<file-location>
Overriding properties through command line
Another way to override the properties is directly passing them through command line arguments.
For example if property which you want to reset is server.port then it can be set as below.
java -jar <yourapp.jar> — server.port=1010