Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's suppose I have this @Configuration class:

@Configuration
public class SomeConfig{

    @Bean
    public MyBean myBean(){
         return new MyBean();
    } 

    @Bean
    public Another anotherBean(){
         return new AnotherBean();
    }
}

I have a class that implements BeanDefinitionRegistryPostProcessor to add certain BeanDefinitions. 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);
}

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
like image 641
codependent Avatar asked Jan 03 '17 11:01

codependent


1 Answers

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

like image 127
codependent Avatar answered Sep 27 '22 18:09

codependent