garyj garyj - 1 month ago 9x
Java Question

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

I am trying to use @Value annotation in the parameters of a constructor as follows:

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
@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}

algorithm = ${encryptor.algorithm:"PBEWithMD5AndTripleDES"}

rather than the expected

poolSize = 10

algorithm = "PBEWithMD5AndTripleDES"

Based on SPR-4785 the notation such as ${} should work. Yet it's not happening for me!

Thank you


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.