Stefan B
Stefan B

Reputation: 41

Using placeholders in Annotations on Spring Java Configurations

I'm a little bit lost in Spring's Property Replacement mechanism. Lets say I have this Java Config

@Configuration
@ComponentScan(basePackageClasses = Application.class)
@PropertySources({
    @PropertySource("classpath:/config/default.properties")
})
public class ApplicationConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    return pspc;
}

Now I want to add a Spring-Data Annotation @EnableMongoRepositories and define a custom basepackage for scanning, using a custom placeholder like follows @EnableMongoRepositories("${my.custom.repobasepackage}"). The Placeholder is defined in my default.properties.

However, this property cannot be resolved here. When diving deeper into Spring's property replacement, I can see that it tries to resolve the property, so it is possible to do so.

However, the underlying Environment class which is used to replace the placeholder does not know about my PropertyPlaceholderConfigurer, but only know about my SystemProperties and my VM-Props. :-(

I can see that in org.springframework.context.annotation.ClassPathBeanDefinitionScanner#getOrCreateEnvironment.java#339 (I'm using Spring 4.0.1) my "PropertyPlaceholder" is already in place, so its not a question of ordering in initialization, but is not used, because the used BeanDefinitionRegistry does not implement the Interface EnvironmentCapable. Here, my understanding of the Spring App-Context Bootstrapping is at the end.

Can anybody help me out here? Is there a BeanDefinitionRegistry out there which is capable of providing the Environment Instance which uses my Property Placeholder?

Any help is highly appreciated!! I got cookies for you! :-))

Cheers, Stefan

Upvotes: 2

Views: 1892

Answers (1)

Dave Syer
Dave Syer

Reputation: 58114

I imagine that the @PropertySources (you only have one by the way so you don't need the wrapper) are added to the Environment after the config classes are processed, so it will be too late to resolve on one of the annotations of those classes themselves. You can verify this by setting my.custom.repobasepackage as a System property.

As an alternative I encourage you to try out Spring Boot (where application.properties is added to the Environment before any configuration is processed).

Upvotes: 1

Related Questions