简体   繁体   中英

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

Using a construct such as

@Component
public class SomeClass {

    @Inject
    private Environment env;

    private String key;


    @PostConstruct
    private void init() {

        key = env.getProperty("SOME_KEY_PROPERTY");

    }

    ....
}

it is possible to assign some field with some property.

Is there a shorter, more concise form to do this?

@Component
public class SomeClass {

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

    ....
}

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

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

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;

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.

There are 17 ways to override a property value in spring boot, one of them is environment variables (Item 10. in the official documentation

The only trick is that you have to convert property names to to uppercase and underscore. For example if you want to overwrite the property

myApp.myProperty

then you have to have an environment variable called

MYAPP_MYPROPERTY

this means that you can just have

@Value("${myApp.myProperty}")

without any customization and you can still overwrite it with an environment variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM