Spring @Value annotated method, use default value

2020-05-23 19:54发布

问题:

Situation

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.

Problem

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}"

Here is the annotated field:

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

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

回答1:

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;


回答2:

Just use:

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


回答3:

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


回答4:

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
}