Reputation: 2092
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.
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.
Upvotes: 28
Views: 53536
Reputation: 1
@value(key.name:xyz)
Spring will give the first priority to read the value from the property file, If that doesn't exist then it will takes the default value(here 'xyz' is the default value).
There should not be any space to the key(key.name) before and after.
Upvotes: 0
Reputation: 56
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
}
Upvotes: -7
Reputation: 10139
@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;
Upvotes: 3
Reputation: 2146
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;
Upvotes: 42
Reputation: 34460
Just use:
@Value("${secret:default-secret-value}")
private String ldapSecret;
Upvotes: 7