Search code examples
springpropertiesconfigurationspring-bootconfiguration-files

How to load beans based on custom properties


I have custom implementation of PropertySourcesPlaceholderConfigurer, which I'm using to load additional property sources and placing them into different position (one on the end, and one before systemProperties). So properties can be overridden on different level.

Based on some properties, I need to load set of beans. For that I'm implementing ImportBeanDefinitionRegistrar.

Unfortunately that ImportBeanDefinitionRegistrar is executed before PropertySourcesPlaceholderConfigurer. I also tried to use @ConditionalOnProperty, with the same result. And with PropertySourceFactory which is executed on the early beginning, but at that point I can't position those additional property sources.

Is there a way to add additional PropertySource in custom order before ImportBeanDefinitionRegistrar, or on the early beginning of Spring lifecycle?

Here I have sandbox app to play with the concept. In reality I have this as in house library for Spring and Spring Boot applications, to enable additional functionalities with properties.


Solution

  • You should implement EnvironmentPostProcessor and move all the logic for the property sources there. You current project is broken in the sense that you have no guarantee that @PropertySource is going to be processed early (actually, it won't).