Read System environment variable in Spring Boot
This post will discuss how to read the system environment variable (OS-level variables) in a Spring Boot application.
When Spring Boot initializes its environment, it uses properties files, YAML files, environment variables, and command-line arguments to externalize the configuration. This post will discuss how to read the system environment variable.
1. Spring’s Environment Interface
The property values can be accessed through Spring’s Environment abstraction, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class Details implements EnvironmentAware { private String url; @Override public void setEnvironment(Environment env) { this.url = env.getProperty("spring.datasource.url"); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } |
Another alternative is to simply inject Environment into our controller/bean.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class Details { @Autowired private Environment env; public String getUrl() { return env.getProperty("spring.datasource.url"); } } |
2. @Value annotation
We can also use the @Value annotation to load variables from the application.properties.
Suppose in application.properties, we have a property spring.datasource.url. Then the property values can be injected directly into your beans by using the @Value annotation, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Details { @Value("${spring.datasource.url}") private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } |
That’s all about reading the System environment variable in Spring Boot.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)