简体   繁体   English

如何在Spring中从本地属性文件动态填充@Value属性?

[英]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. 为了提供通用解决方案,我希望能够在@Value批注中指定一个备份值。 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? 使用@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}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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