by BehindJava

How to read environment variables in SpringBoot

Home » springboot » How to read environment variables in SpringBoot

In this tutorial we are going to learn about reading the environment variables from the through out the application.

Spring Boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.

Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties.

You can do it with the @Value annotation:

private String myVariable;

You can also use colon to give a default value if not found:

private String myVariable;

Alternatively, you can use the org.springframework.core.env.Environment interface to access environment variables:

private Environment env;