Spring Boot applications can be easily configured via property files. But sometimes you need more flexibility in terms of how the configuration is provided to the application. A popular approach next to configuration files is to use environment variables. This post will cover how you can use OS environment variables to pass configuration values to a Spring Boot application.
Injecting environment variables
You might already be familiar with the
It can be used to inject property values to beans.
In addition to looking values from property files, the
@Value annotation also looks for matching values from the environment.
So when you have an environment property called
DB_URL, you can inject it to a field with
application.properties values from environment
Similar to the previous approach, it is possible to assign values to properties in your
application.properties file from the environment.
As with the
@Value annotation, you can provide a default value which will be used if the environment variable is not found.
At application startup, Spring Boot will look for an environment variable called
It can be used to provide a set of application properties using inline JSON.
For example, you can set
ec2.public.url property as follows.
To get a more thorough overview of all the ways Spring Boot allows you to configure applications, you should definitely look at the official docs. You can find an example Sprint Boot application from Github that demonstrates the approaches covered in this post.
📖 Book Recommendation! If you’d like to learn more about Spring Boot, check out Learning Spring Boot 2.0 by Greg L. Turnquist.