Reading OS environment variables in spring boot application using @Value annotation

There are multiple ways to access system environment varibles in a spring boot application using @Value annotation.

The simplest way is to use normal property access with ${} scheme. Spring boot automatically reads environment variables and system properties, makes it accessible as normal properties. You should only replace underscores with dots if the environment variable contains any. For example if you want to access JAVA_HOME you have to transform it as java.home or JAVA.HOME (it is not case sensitive) .

private String javaHome;

Alternatively you can use SpEL (Spring Execution Language). One of the powerful abilities of SpEL is accessing Collections, Arrays, Lists or Properties. While spring intializes our application it collects informations from execution environment including system environments, system properties, application properties etc. and aggregate them in an Environment object. So we can access this object with SpEL to read an environment variable. Here we need slightly different signature compared to above example. Instead of ${ …} we have to write #{ spel.statement }.

private String javaHome;

The second alternative is quite similar to latest. Here we use systemEnvironment instead of environment.

private String javaHome;

The systemEnvironment is a key-value Map, which contains only system environment variables and their values, where environment is a StandardEnvironment object which is a collection of different property sources (bootstrap, systemProperties, systemEnvironment, random, integrationTest, applicationConfig: [classpath:/], defaultProperties, Management Server).

Leave a reply