Using environment variables with Spring Boot

Photo Credit: Gustavo QuepĆ³n

Using environment variables with Spring Boot

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 @Value annotation. 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 @Value("${DB_URL}").

private String dbUrl;

Setting values from environment

Similar to the previous approach, it is possible to assign values to properties in your 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 SPRING_APPLICATION_JSON. 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.

comments powered by Disqus