Spring Boot自动配置命令 [英] Spring Boot auto-configuration order
问题描述
我想创建一个Spring Boot自动配置类,它(有条件地)创建一个bean A
。但挑战是,必须在另一个bean B
之前创建一个Spring Boot的默认自动配置类。 bean B
不依赖于 A
。
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
.
我的第一次尝试是使用 @AutoConfigureBefore
。这不符合我的预期和判断,来自Dave Syer的此评论不应该。
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.
一些背景:前面提到的bean A
改变一个Mongo数据库,这必须在 MongoTemplate
已创建。
Some background: The aforementioned bean A
alters a Mongo Database and this has to happen before MongoTemplate
is created.
推荐答案
事实证明,我想要的是动态地使 B
的实例依赖于 A
。这可以通过使用 BeanFactoryPostProcessor
来实现改变 B
bean的bean定义。
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");
}
}
}
这适用于普通的Spring,不需要Spring Boot。要完成自动配置,我需要添加bean定义 DependsOnPostProcessor
到实例化bean的配置类 A
。
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
.
这篇关于Spring Boot自动配置命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!