java-BeanDefinitionRegistryPostProcessor-如何将@Configuration类注册为BeanDefinition并获取其@Beans
作者:互联网
假设我有这个@Configuration类:
@Configuration
public class SomeConfig{
@Bean
public MyBean myBean(){
return new MyBean();
}
@Bean
public Another anotherBean(){
return new AnotherBean();
}
}
我有一个实现BeanDefinitionRegistryPostProcessor的类,以添加某些BeanDefinitions.在此我也想导入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
解决方法:
它之所以没有导入@Beans,是因为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 ();
}
}
->>这将无法导入豆子<<-
标签:spring-bean,spring,java,spring-mvc 来源: https://codeday.me/bug/20191026/1936108.html