Spring @Value带注释的方法,当属性不可用时使用默认值

Ren*_*cic 10 java spring spring-annotations properties-file spring-boot

情况

我将.properties文件中的属性注入到使用@Value注释的字段中.但是,此属性提供敏感凭据,因此我将其从存储库中删除.我仍然希望如果有人想要运行项目并且没有.properties文件,其凭据将默认值设置为字段.

问题

即使我将默认值设置为字段本身,当.properties文件不存在时,我也会遇到异常:

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}"
Run Code Online (Sandbox Code Playgroud)

这是带注释的字段:

 @Value("${secret}")
 private String ldapSecret = "secret";
Run Code Online (Sandbox Code Playgroud)

我预计在这种情况下只会设置普通字符串"secret".

Ber*_*enz 10

完全回答你的问题......

@Value("${secret:secret}")
private String ldapSecret;
Run Code Online (Sandbox Code Playgroud)

以下是一些示例完整性的变化......

将String默认为null:

@Value("${secret:#{null}}")
private String secret;
Run Code Online (Sandbox Code Playgroud)

默认数字:

@Value("${someNumber:0}")
private int someNumber;
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,但它没有解决问题.它解释了系统如何支持工作,但截至2017年10月,Spring 4.2.4,它实际上并没有那样工作.如果在@value注释中指定默认值,则不会使用属性文件中的实际值.如果从注释中删除默认值,则使用属性文件中的值 - 除非它丢失,在这种情况下,尝试实例化Bean时会抛出异常. (4认同)
  • 从 2020 年 2 月开始,如果有默认值,Spring 将看不到属性文件中的值。无法同时使用默认值和属性文件中的值 (2认同)
  • 仅当我们在注释中添加“value=”时,这种定义默认值的方法才有效。例如,如果在配置文件中找不到属性,@Value(value="${secret:secret}") 将使用默认值。 (2认同)

Fed*_*ner 6

只需使用:

@Value("${secret:default-secret-value}")
private String ldapSecret;
Run Code Online (Sandbox Code Playgroud)