BeanDefinitionRegistryPostProcessor - 如何将@Configuration类注册为BeanDefinition并同时注册其@Beans

时间:2017-01-03 11:39:29

标签: java spring spring-mvc spring-bean

假设我有@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(myBeananotherBean)尚未被添加到上下文中。但是有一些someConfig bean:

@Autowired
MyBean myBean   ---> FAILS

@Autowired
AnotherBean anotherBean   ---> FAILS

@Autowired
SomeConfig someConfig   ---> OK

1 个答案:

答案 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<<--