I am trying to use @Value annotation in the parameters of a constructor as follows:
@Autowired public StringEncryptor( @Value("${encryptor.password:\"\"}") String password, @Value("${encryptor.algorithm:\"PBEWithMD5AndTripleDES\"}") String algorithm, @Value("${encryptor.poolSize:10}") Integer poolSize, @Value("${encryptor.salt:\"\"}") String salt) { ... }
When the properties file is present on the classpath, the properties are loaded perfectly and the test executes fine. However when I remove the properties file from the classpath, I would have expected that the default values would have been used, for example poolSize would be set to 10 or algorithm to PBEWithMD5AndTripleDES however this is not the case.
Running the code through a debugger (which would only work after changing @Value("${encryptor.poolSize:10}") Integer poolSize
to @Value("${encryptor.poolSize:10}") String poolSize
as it was causing NumberFormatExceptions) I find that the defaults are not being set and the parameters are in the form of:
poolSize = ${encryptor.poolSize:10}
or
algorithm = ${encryptor.algorithm:"PBEWithMD5AndTripleDES"}
rather than the expected
poolSize = 10
or
algorithm = "PBEWithMD5AndTripleDES"
Based on SPR-4785 the notation such as ${my.property:myDefaultValue} should work. Yet it's not happening for me!
Thank you
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.
Spring @Value annotation 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. Spring @Value annotation also supports SpEL.
@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.
The values are true and false. @Value("true") private boolean isReadOnly; @Value with default date value – A date can be set as default value in the annotation @Value in spring boot. The java date format has to be specified to parse the date.
Perhaps initialization of property placeholder configurer fails due to missed properties file, so that placeholders are not resolved. You can configure it to ignore missed files as follows (if you use context
namespace to configure it):
<context:property-placeholder ignore-resource-not-found="true" ... />
Also you don't need "..."
around default values.
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