Spring Boot auto-configuration order

前端 未结 3 2061
广开言路
广开言路 2021-01-01 07:14

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

3条回答
  •  一向
    一向 (楼主)
    2021-01-01 08:00

    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.

提交回复
热议问题