hzpz hzpz - 23 days ago 4
Java Question

Spring Boot auto-configuration order

I want to create a Spring Boot auto-configuration class that (conditionally) creates a single bean

. The challenge however is, that this been has to be created before another bean
is created in one of Spring Boot's default auto-configuration classes. The bean
does not depend on

My first try was to use
. That didn't work the way I expected and judging from this comment by Dave Syer it shouldn't.

Some background: The aforementioned bean
alters a Mongo Database and this has to happen before
is 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 {

    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.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.