问题
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;
来源:https://stackoverflow.com/questions/43238583/spring-value-annotated-method-use-default-value-when-properties-not-available