Java Spring: How to use `@Value` annotation to inject an `Environment` property?

Solution 1:

@Component
public class SomeClass {

    @Value("#{environment.SOME_KEY_PROPERTY}")
    private String key;

    ....
}

Solution 2:

You should be able to do this(assuming that you have a PropertySourcesPlaceHolderConfigurer registered)

@Value("${SOME_KEY_PROPERTY}")
private String key;

Solution 3:

You might also find it useful to provide a default value in case the variable is not defined:

@Value("${some_property:default_value}")
private String key;

Otherwise you'll get an exception whenever some_property is not defined.

default_value can also be blank, in that case it will behave as if some_property was optional:

@Value("${some_property:}")
private String key;

(Notice the colon)

If the default value contains special characters (dot, colon, etc.), then wrap it in SpEL like this:

@Value("${some_property:#{'default_value'}}")
private String key;

Solution 4:

If you need to add an environment variable as default value.

@Value("${awsId:#{environment.AWS_ACCESS_KEY_ID}}")
@Value("${awsSecret:#{environment.AWS_SECRET_ACCESS_KEY}}")

This is a combination of two previous answers.