I am trying to use @Value annotation in the parameters of a constructor as follows:
@Autowired
public StringEncryptor(
@Value(\"${encryptor.password:\\\"\\\"
In my case, resolving the property values (and the defaults) did not work in test, where I use an annotation based configuration. It turned out that I had to add a PropertySourcesPlaceholderConfigurer
so that properties actually get resolved. It was explained in the PropertySource Annotation JavaDoc:
In order to resolve ${...} placeholders in definitions or @Value annotations using properties from a PropertySource, one must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using in XML, but must be explicitly registered using a static @Bean method when using @Configuration classes. See the "Working with externalized values" section of @Configuration Javadoc and "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean Javadoc for details and examples.
The following did the trick:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
And if you want to add individual properties:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
Properties properties = new Properties();
properties.put("batchSize", "250");
propertySourcesPlaceholderConfigurer.setProperties(properties);
return propertySourcesPlaceholderConfigurer;
}