我想创建一个 Spring Boot 自动配置类(有条件地)创建单个 bean A
。然而,挑战在于,必须在 Spring Boot 的默认自动配置类之一中创建另一个 bean B
之前创建它。 bean B
不依赖于 A
。
我的第一次尝试是使用@AutoConfigureBefore
。从 this comment 来看,这并没有按照我的预期工作。作者:Dave Syer 它不应该。
一些背景:前面提到的 bean A
会更改 Mongo 数据库,并且这必须在创建 MongoTemplate
之前发生。
最佳答案
事实证明,我想要的是动态地使 B
的实例依赖于 A
。这可以通过使用 BeanFactoryPostProcessor
来实现 alter the bean definitions 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");
}
}
}
这适用于普通 Spring,不需要 Spring Boot。为了完成自动配置,我需要将 DependsOnPostProcessor
的 bean 定义添加到实例化 bean A
的配置类中。
关于java - Spring Boot 自动配置顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692905/