Java Spring@Value注释方法,当属性不可用时使用默认值 处境
我正在将.properties文件中的属性注入到带有@Value注释的字段中。但是,这些属性表示敏感凭据,所以我将它们从存储库中删除。我仍然希望这样,以防有人想要运行项目,但没有带有凭据的.properties文件,默认值将设置为字段 问题 即使将默认值设置为字段本身,当.properties文件不存在时,也会出现异常:Java Spring@Value注释方法,当属性不可用时使用默认值 处境,java,spring,spring-boot,spring-annotations,properties-file,Java,Spring,Spring Boot,Spring Annotations,Properties File,我正在将.properties文件中的属性注入到带有@Value注释的字段中。但是,这些属性表示敏感凭据,所以我将它们从存储库中删除。我仍然希望这样,以防有人想要运行项目,但没有带有凭据的.properties文件,默认值将设置为字段 问题 即使将默认值设置为字段本身,当.properties文件不存在时,也会出现异常: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '
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”。只需使用:
@Value("${secret:default-secret-value}")
private String ldapSecret;
要准确回答你的问题
@Value("${secret:secret}")
private String ldapSecret;
下面还有一些变化,以确保示例的完整性
默认字符串为空:
@Value("${secret:#{null}}")
private String secret;
默认数字:
@Value("${someNumber:0}")
private int someNumber;
实际上,将始终使用默认值。为了克服这个问题,我使用了一个字符串值
@Value("${prop}")
String propValue;//if no prop defined, the propValue is set to the literal "${prop}"
....
if("${prop}".equals(propValue)) {
propValue=defaultValue
}
您的可能副本可以说明Spring表达式语言可以用于解决此问题。例如,
@Value(“${secret:{null}”)
。这是一个很好的答案,但并不能解决问题。它解释了系统应该如何工作,但截至2017年10月,Spring 4.2.4,它实际上并没有以这种方式工作。如果在@value注释中指定默认值,则不会使用属性文件中的实际值。如果从注释中删除默认值,那么将使用属性文件中的值——除非缺少该值,在这种情况下,尝试实例化Bean时会引发异常。从2020年2月起,如果存在默认值,Spring将看不到属性文件中的值。无法同时使用默认值和属性文件中的值。只有在注释中添加“value=”时,这种定义默认值的方法才有效。e、 g.@Value(Value=“${secret:secret}”)将在配置文件中找不到属性时使用默认值。这根本不是真的。
@Value("${prop}")
String propValue;//if no prop defined, the propValue is set to the literal "${prop}"
....
if("${prop}".equals(propValue)) {
propValue=defaultValue
}