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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43238583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:13:07  来源:igfitidea点击:

Spring @Value annotated method, use default value when properties not available

javaspringspring-bootspring-annotationsproperties-file

提问by RenatoIvancic

Situation

情况

I am injecting properties from .propertiesfile 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文件中的属性注入到用@Value注释的字段中。但是,此属性提供敏感凭据,因此我将它们从存储库中删除。我仍然希望以防万一有人想要运行项目并且没有带有凭据的 .properties 文件,默认值将设置为字段。

Problem

问题

Even if I set default values to field itself I get exception when .properties file is not present:

即使我将默认值设置为字段本身,当 .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}"

Here is the annotated field:

这是带注释的字段:

 @Value("${secret}")
 private String ldapSecret = "secret";

I expected in this case just plain String "secret" would be set.

我希望在这种情况下只设置简单的字符串“秘密”。

回答by Bernie Lenz

To answer your question exactly...

准确回答你的问题...

@Value("${secret:secret}")
private String ldapSecret;

And a few more variations are below for completeness of the examples...

为了示例的完整性,下面还有一些变化......

Default a String to null:

默认字符串为空:

@Value("${secret:#{null}}")
private String secret;

Default a number:

默认一个数字:

@Value("${someNumber:0}")
private int someNumber;

回答by Federico Peralta Schaffner

Just use:

只需使用:

@Value("${secret:default-secret-value}")
private String ldapSecret;

回答by Ahmet Karakaya

@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;

回答by Vinh

Actually the default value will be ALWAYS used. To overcome this, I use a String value

实际上,将始终使用默认值。为了克服这个问题,我使用了一个字符串值

@Value("${prop}")
String propValue;//if no prop defined, the propValue is set to the literal "${prop}"
....
if("${prop}".equals(propValue)) {
     propValue=defaultValue
}