98

What is the best way to read environment variables in SpringBoot?
In Java I did it using:

String foo = System.getenv("bar");

Is it possible to do it using @Value annotation?

1
  • 1
    Spring's Environment abstraction automatically reads all environment variables; you do not need to read them yourself. To obtain the value from the Environment bean, use @Value as many have posted below. Commented May 27, 2024 at 18:04

12 Answers 12

98

Quoting the documentation:

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.

So, since Spring boot allows you to use environment variables for configuration, and since Spring boot also allows you to use @Value to read a property from the configuration, the answer is yes.


For example, the following will give the same result:

@Component
public class TestRunner implements CommandLineRunner {
    @Value("${bar}")
    private String bar;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void run(String... strings) throws Exception {
        logger.info("Foo from @Value: {}", bar);
        logger.info("Foo from System.getenv(): {}", System.getenv("bar")); // Same output as line above
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

What todo If I want to use this in a @Entity class, e.g. for a getter?
1. Value is perfect for small number of injected env vars. 2. ConfigurationProperties is perfect for multiple vars(4+) Both options are easy to manage in unit tests All other options to inject are not recommended
You can use @Value for variables and @ConfigurationProperties for a group of variables. x @Value("${MY_ENV_VAR:defaultValue}") // defaultValue is optional private String myEnvVar; @Component @ConfigurationProperties(prefix = "myapp") @Data public class MyAppProperties { private String host; private int port; }
69

You can do it with the @Value annotation:

@Value("${bar}")
private String myVariable;

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

@Value("${bar:default_value}")
private String myVariable;

1 Comment

Works only in initialized components, dows not work in main class from static main function.
27

Here are three "placeholder" syntaxes that work for accessing a system environment variable named MY_SECRET:

@Value("${MY_SECRET:aDefaultValue}")
private String s1;

@Value("#{environment.MY_SECRET}")
private String s2;

@Value("${myApp.mySecretIndirect:aDefaultValue}") // via application property
private String s3;

In the third case, the placeholder references an application property that has been initialized from the system environment in a properties file:

myApp.mySecretIndirect=${MY_SECRET:aDefaultValue}

For @Value to work, it must be used inside a live @Component (or similar). There are extra gochas if you want this to work during unit testing -- see my answer to Why is my Spring @Autowired field null?

3 Comments

Notice the different punctuation #{ vs ${ when using environment..
I think you have a typo @Value("#{environment.MY_SECRET}") should be with $
@dgraf, See the prior comment (by me) -- this is intentional. It's kind of an obscure feature, but you can find it documented by looking for Spring Expression Language (SpEL).
22

Alternatively, you can use the org.springframework.core.env.Environment interface to access environment variables (NOTE: this works only in initialized Spring components):

import org.springframework.core.env.Environment;

@Autowired
private Environment env;

//...

System.out.println(env.getProperty("bar"));

Read more...

1 Comment

Does not work on main static function of @SpringBootApplication class. Works only in initialized Spring components.
2

There are multiple answers to read the environment in code using @Value hence I am not providing that. Below is the example of using environment variable in application.yml file to provide some external values based on different env.

my-service:
  api-base: ${API_BASE:}
  env: ${ENVIRONMENT:prod}

In the above example, the property configuration will use the evironment variables which could be provided externally during application launch, and they will be replaced in here. It also supports the default value if the env var is not provided, as seen for env

Below is my docker-compose.yaml snippet which is providing these variables.

services:
  my-service:
    environment:
        API_BASE: http://example.com/api/v1
        ENVIRONMENT: ci

Comments

1

Yes, you can. However, most answer didn't mention, the ordering is very important, please check this https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html

Your OS environment variables will overwrite the value come from Application properties packaged inside your jar (application.properties and YAML variants)., so basically, your environment variables has higher priority.

Comments

0

In rare cases, if you want to access environment parameters in spring main methods ( which is static ) you can must let Spring application build then use the ApplicationContext to access environment . Something like

public static void main(String[] args) {
            
    ApplicationContext applicationContext = new SpringApplicationBuilder(MyApp.class).run(args);
    Environment environment = applicationContext.getEnvironment();
    System.out.println(environment.getProperty("spring.application.name"));
    System.out.println(environment.getProperty("foo.bar"));
            
}

Comments

0

If you are using springboot, simply place the application.properties or application.yml file in src/main/resources/ or src/main/resources/config/ directory. No need to configure anything else, all beans can directly reference properties using @Value.

Here's the simplest example:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Value("${my.property}")
    private String myProperty;

    public void printProperty() {
        System.out.println("Property value: " + myProperty);
    }
}

In your application.properties file, add:

my.property=Hello,Harry!

This way, when MyComponent is loaded, myProperty will be injected with the value from the application.properties file.

Comments

0

A way to read properties in Spring Boot is by using the @Value annotation for individual properties or by binding them to a configuration class using @ConfigurationProperties. This allows for easy injection of property values from application.properties or application.yml into your components, services, or beans.

@Value("${creds}")
private String creds;

in application.properties file define

creds=32432432432

it will pick value 324324324

Comments

-1

You can place your environment variable in an application.yml/application.properties file and then you can fetch the value using the @Value annotation. But in order to use @Value annotation your class should be a bean and should be annotated with @Component annnotation. You can also provide a default value for the variable.

@Component
@NoArgsConstructor
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MyClass {
 
@Value("${something.variable:<default-value>}")
private String myEnvVariable;

}
    

1 Comment

A value defined in application.yml or application.properties is NOT an environment variable.
-1

You can use it with the @Value annotation for the @Components and @service class.

Sometimes it won't work if it is a normal class.

Example:

@Component
public class Testclass{
    @Value("${MY_SECRET:aDefaultValue}")
    private String test1;

    @Value("#{environment.MY_SECRET}")
    private String test2;

    @Value("${myApp.mySecretIndirect:aDefaultValue}")
    private String test3;

    //to get the properties list which are in "," separated
    @Value("${my.list.of.strings}")
    private List<String> myList;
}

Comments

-2

First, you have to define the relevant field information in the properties configuration file, and then use @ value to obtain and use example:

@Value("${abc}")
private String abc;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.