Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Spring ApplicationContext inside of BeanDefinitionRegistryPostProcessor

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?

like image 365
Neo Avatar asked Oct 20 '25 15:10

Neo


1 Answers

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();
like image 98
gorodkovskaya Avatar answered Oct 23 '25 07:10

gorodkovskaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!