hzpz hzpz - 2 months ago 21
Java Question

Spring Boot auto-configuration order

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 before another bean
B
is created in one of Spring Boot's default auto-configuration classes. The bean
B
does not depend on
A
.

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

Some background: The aforementioned bean
A
alters a Mongo Database and this has to happen before
MongoTemplate
is created.

Answer

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.