Using environment variables with Spring Boot

Photo by Gustavo Quepón

Indrek Ots
by Indrek Ots
1 min read

Categories

  • articles

Tags

  • spring
  • spring boot
  • java

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

@Value("${DB_URL}")
private String dbUrl;

Setting 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.

api.key=${API_KEY}

As with the @Value annotation, you can provide a default value which will be used if the environment variable is not found.

api.key=${API_KEY:123abc}

SPRING_APPLICATION_JSON

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.

SPRING_APPLICATION_JSON='{"ec2":{"public":{"url":"http://mydomain.com"}}}'

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.

This website is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.