I have been trying to use variable replacements inside @Value annotations using the new @PropertySource mechanism. What I've found is that for each class I annotated with @PropertySource and @Configuration required a static Bean definition for the PropertySourcesPlaceholderConfigurer. The way I read the spring documentation was that the PropertySourcesPlaceholderConfigurer was only needed to be defined once somewhere in the app - NOT in each class with @PropertySource annotations. The example below shows the situation. The code below will replace the ${title} with the value from the respective properties file value in both config classes. If I was to remove the static method in one of the classes that class then no longer will do variable replacements in the @Value annotation.
Is this the correct "spring" way of using @PropertySource with PropertySourcePlaceholderConfigurer?
component-a.properties
title=Component A
component-b.properties
title=Component B
BeanA.java
class BeanA {BeanA(String title) { }}
BeanB.java
class BeanB {BeanB(String title) { }}
ComponentAConfig.java
@Configuration
@PropertySource("classpath:/component-a.properties")
public class ComponentAConfig {
@Value("${title}")
private String title;
@Bean
public BeanA createBeanA() {
BeanA bean = new BeanA(title);
return bean;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
ComponentBConfig.java
@Configuration
@PropertySource("classpath:/component-b.properties")
public class ComponentBConfig {
@Value("${title}")
private String title;
@Bean
public BeanB createBeanB() {
BeanA bean = new BeanB(title);
return bean;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}


Reply With Quote