Spring @Value 注解方法,当属性不可用时使用默认值
Spring @Value annotated method, use default value when properties not available
情况
我正在将 .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}"
这是带注释的字段:
@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 and Property Examples
To set a default value for property placeholder :
${property:default value}
Few examples :
//@PropertySource("classpath:/config.properties}")
//@Configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongodbUrl;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
实际上将始终使用默认值。为了克服这个问题,我使用了一个字符串值
@Value("${prop}")
String propValue;//if no prop defined, the propValue is set to the literal "${prop}"
....
if("${prop}".equals(propValue)) {
propValue=defaultValue
}
情况
我正在将 .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}"
这是带注释的字段:
@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 and Property Examples
To set a default value for property placeholder :
${property:default value}
Few examples :
//@PropertySource("classpath:/config.properties}")
//@Configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongodbUrl;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
实际上将始终使用默认值。为了克服这个问题,我使用了一个字符串值
@Value("${prop}")
String propValue;//if no prop defined, the propValue is set to the literal "${prop}"
....
if("${prop}".equals(propValue)) {
propValue=defaultValue
}