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.
To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.
We know now, that we can use the @Value annotation for methods as a global value or as a parameter value.
One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL).
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;
Just use:
@Value("${secret:default-secret-value}")
private String ldapSecret;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With