简体   繁体   中英

How to dynamically populate @Value property from local property file in Spring?

I am having an issue setting up a property that I need to use in my code. In my class, I've declared a property like so:

@Value("${foo.password}")
private String fooPassword;

This would normally be fine, but there is a bit of a wrinkle when it comes to how the property file I'm pulling from is stored in other environments. In all of our upper environments, our value is stored encrypted. However, in our Dev environment, we don't have the ability to decrypt the value so we must store it decrypted. The encrypted values are stored with one key, while the decrypted values are stored with another key.

In order to make a generic solution, I'd love to be able to specify a backup value in the @Value annotation. Something like...

@Value("${foo.passwordEncrypted ? foo.passwordDecrypted }")
private String fooPassword;

... so in the Dev environment it can grab the decrypted value, while the upper environemnts it can grab the encrypted value and do what it needs to do.

Is this something that can be achieved with @Value? Is it possible to create our own custom annotation that could do something similar?

I believe you are looking for a "default" value? In that case use it this way

@Value("${foo.passwordEncrypted:default_decrypted_value}")

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