BeanDefinitionRegistryPostProcessor - How to register a @Configuration class as BeanDefinition and get its @Beans registered as well

前端 未结 1 1930
无人共我
无人共我 2021-02-09 15:49

Let\'s suppose I have this @Configuration class:

@Configuration
public class SomeConfig{

    @Bean
    public MyBean myBean(){
         return new          


        
1条回答
  •  天命终不由人
    2021-02-09 16:45

    There reason why it didn't import the @Beans 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", someConfig);
        }
    
        @Override
        public int getOrder() {
            return Ordered.HIGHEST_PRECEDENCE;
        }
    }
    

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

    0 讨论(0)
提交回复
热议问题