Spring @Value注释方法,当属性不可用时使用默认值 [英] Spring @Value annotated method, use default value when properties not available
问题描述
我正在将 .properties 文件中的属性注入带有 @Value 的字段中.但是,此属性提供敏感的凭据,因此我将它们从存储库中删除.如果有人要运行项目并且没有带有凭据的.properties文件(默认值将设置为字段),我仍然希望这样做.
I am injecting properties from .properties file into fields annotated with @Value. However this properties present sensitive credentials, so I remove them from repository. I still want that in case someone wants to run project and doesnt have .properties file with credentials that default values will be set to fields.
即使我将默认值设置为字段本身,当.properties文件不存在时,也会出现异常:
Even if I set default values to field itself I get exception when .properties file is not present:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxx': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'secret' in string value "${secret}"
这是带注释的字段:
@Value("${secret}")
private String ldapSecret = "secret";
在这种情况下,我希望只设置纯字符串"secret".
I expected in this case just plain String "secret" would be set.
推荐答案
要准确回答您的问题...
To answer your question exactly...
@Value("${secret:secret}")
private String ldapSecret;
为了示例的完整性,下面还有更多变体...
And a few more variations are below for completeness of the examples...
默认字符串为空:
@Value("${secret:#{null}}")
private String secret;
默认数字:
@Value("${someNumber:0}")
private int someNumber;
这篇关于Spring @Value注释方法,当属性不可用时使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!