I want to create a Spring Boot auto-configuration class that (conditionally) creates a single bean A. The challenge however is, that this been has to be created
It turns out, what I want is to dynamically make instances of B depend on A. This can be achieved by using a BeanFactoryPostProcessor to alter the bean definitions of B beans.
public class DependsOnPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, B.class, true, false);
for (String beanName : beanNames) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
definition.setDependsOn(StringUtils.addStringToArray(
definition.getDependsOn(), "beanNameOfB");
}
}
}
This works with plain Spring, no Spring Boot required. To complete the auto-configuration I need to add the bean definition for the DependsOnPostProcessor to the configuration class that instantiates the bean A.