Issue
How does one access the ApplicationContext
inside of a BeanDefinitionRegistryPostProcessor
(BDRPP)? I have the following BDRPP.
public class MyCustomBeansFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// Need to access ApplicationContext here
System.out.println("Got Application Context: " + applicationContext);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}
Tried adding @Autowired and even made my CustomBDRPP implement ApplicationContextAware
but the ApplicationContext is not injected/initialized.
public class MyCustomBeansFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
//@Autowired
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("Got Application Context: " + applicationContext);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}
Output:
Got Application Context: null
How can this be achieved?
Solution
I had a similar task and declaring BDRPP as a Bean worked:
public class MyCustomBdrpp implements BeanDefinitionRegistryPostProcessor {
private ApplicationContext context;
private MyCostomBdrpp(ApplicationContext context) {
this.context = context;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
//foo
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
//bar
}
}
And then:
@Configuration
class MyConfig {
@Bean
public MyCustomBdrpp myBdrpp(@Autowired ApplicationContext context) {
return new MyCustomBdrpp(context);
}
}
But I need to say that I am creating context manually:
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MyConfig.class);
context.refresh();
Answered By - gorodkovskaya