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
1

There are 1 answers

3
codependent On BEST ANSWER

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