Spring @Value annotation not using defaults when property is not present

Posted by garyj on Stack Overflow See other posts from Stack Overflow or by garyj
Published on 2011-01-15T07:49:01Z Indexed on 2011/01/15 7:53 UTC
Read the original article Hit count: 182

Filed under:
|
|

Hi All

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

© Stack Overflow or respective owner

Related posts about java

Related posts about spring