假设我有@Configuration
课程:
@Configuration
public class SomeConfig{
@Bean
public MyBean myBean(){
return new MyBean();
}
@Bean
public Another anotherBean(){
return new AnotherBean();
}
}
我有一个实现BeanDefinitionRegistryPostProcessor
的类来添加某些BeanDefinition
。在它上面我还想导入SomeConfig
,以便将其bean添加到上下文中:
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition someConfig= new RootBeanDefinition("x.y.z.SomeConfig");
registry.registerBeanDefinition("someConfig", someConfig);
}
问题是SomeConfig
的bean(myBean
,anotherBean
)尚未被添加到上下文中。但是有一些someConfig bean:
@Autowired
MyBean myBean ---> FAILS
@Autowired
AnotherBean anotherBean ---> FAILS
@Autowired
SomeConfig someConfig ---> OK
答案 0 :(得分:4)
为什么它没有导入@Bean
的原因是我的后处理器之前执行了ConfigurationClassPostProcessor
所以没有添加新的bean。为了解决这个问题,我实施了PriorityOrdered
:
@Configuration
public class MyFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered{
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition someConfig= new RootBeanDefinition("x.y.z.SomeConfig");
registry.registerBeanDefinition("someConfig", enableOAuth2ClientBd);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
重要后处理器类为@Configuration
并且直接在配置中导入,未在另一个@Configuration
类中定义定义为@Bean:
@Configuration
public class BeanDefinitionFactoryTestConfig {
@Bean
public MyFactoryPostProcessor cc(){
return new MyFactoryPostProcessor ();
}
}
<强> -->> THIS WILL FAIL TO IMPORT THE BEANS<<--
强>