Reputation: 343
In my non-Boot Spring 5 project I need to manually register and initialize some beans. After that I want to add a @Configuration
class to context, that imports a config from an external lib:
@Configuration
@Import(ExtLibConfig.class)
public class MyExtLibConfig {
@Bean
public ExtLibBean extLibBean() {
return ExtLibBean.builder().build();
}
}
ExtLibConfig
has many of its own @ComponentScan
and @Import
, and I wish them all to be configured automatically, including my ExtLibBean
.
Is it possible to do so in runtime? External lib scans ApplicationContext
, and I need it to do so, when my manually registered beans are added.
UPD:
The problem is not actual about beans register order. The ext lib is scanning ApplicationContext
after its refresh, so I need my beans to be there at this time
Upvotes: 4
Views: 769
Reputation: 343
The solution was to implement BeanDefinitionRegistryPostProcessor
public class MyMockBeanDefinitioRegistrynPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// registry.registerBeanDefinition(mockBeanClass, mockBeanDefinition);...
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// nothing to do
}
Then declare it as a Bean
:
@Configuration
public class MockBeanConfig {
@Bean
public MyMockBeanDefinitioRegistrynPostProcessor mockBeanDefinitionPp() {
return new MyMockBeanDefinitioRegistrynPostProcessor();
}
}
And add it to context:
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MockBeanConfig.class);
context.register(MyExtLibConfig.class);
context.refresh();
Upvotes: 1