BeanDefinitionRegistryPostProcessor - 如何将@Configuration类注册为BeanDefinition并获取其@Beans注册 [英] BeanDefinitionRegistryPostProcessor - How to register a @Configuration class as BeanDefinition and get its @Beans registered as well
问题描述
假设我有这个 @Configuration
类:
@Configuration
public class SomeConfig{
@Bean
public MyBean myBean(){
return new MyBean();
}
@Bean
public Another anotherBean(){
return new AnotherBean();
}
}
我有一个实现 BeanDefinitionRegistryPostProcessor
添加某些 BeanDefinition
。在它上面我还想导入 SomeConfig
,以便将其bean添加到上下文中:
I have a class that implements BeanDefinitionRegistryPostProcessor
to add certain BeanDefinition
s. On it I also would like to import SomeConfig
so that its beans are added to the context:
@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:
The problem is that SomeConfig
's beans (myBean
, anotherBean
) haven't been added to the context. There is a someConfig bean though:
@Autowired
MyBean myBean ---> FAILS
@Autowired
AnotherBean anotherBean ---> FAILS
@Autowired
SomeConfig someConfig ---> OK
推荐答案
之所以没有导入 @Bean
s是我的后处理器之前执行了 ConfigurationClassPostProcessor
所以没有添加新的bean。为了解决这个问题,我实现了 PriorityOrdered
:
There reason why it didn't import the @Bean
s was that ConfigurationClassPostProcessor
was executed before my postprocessor so the new beans weren't added. To solve it I implemented 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 $ c中定义$ c>类定义为@Bean:
It's also important that the postprocessor class is @Configuration
and is imported directly in the config, not defined in another @Configuration
class with it defined as @Bean:
@Configuration
public class BeanDefinitionFactoryTestConfig {
@Bean
public MyFactoryPostProcessor cc(){
return new MyFactoryPostProcessor ();
}
}
- >>这将无法进口豆子<< -
-->> THIS WILL FAIL TO IMPORT THE BEANS<<--
这篇关于BeanDefinitionRegistryPostProcessor - 如何将@Configuration类注册为BeanDefinition并获取其@Beans注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!