سؤال

There's a way to programatically add a beanPostProcessor to a ClassPathXmlApplicationContext ?

I can do it declaratively in the xml, but apparently there's no way to add programatically.

My processor must do something like if my bean is a MyInterfaceAware, then do setMyInterface(...).

I need to do it in code cause MyInterface implementation is instantiated in code, it's not available when starting the XML.

I'm using Spring 3.1.2.RELEASE.

Thanks,

... this is what I'm doing ...

public void setSpringBeanFactory(BeanFactory beanFactory) {
    this.beanFactory = (ApplicationContext) beanFactory;
    ((ClassPathXmlApplicationContext) beanFactory).getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {

        public Object postProcessBeforeInitialization(Object bean,
                String beanName) throws BeansException {
            return bean;
        }

        public Object postProcessAfterInitialization(Object bean,
                String beanName) throws BeansException {
            if (bean instanceof RegistryAware)
                ((RegistryAware) bean).setRegistry(ApplicationContextRegistryImpl.this);
            return bean;
        }
    });
    ((ClassPathXmlApplicationContext)beanFactory).refresh();
}
هل كانت مفيدة؟

المحلول

Try with context.getBeanFactory().addBeanPostProcessor(beanPostProcessor)

Edit

You could use a BeanFactoryPostProcessor also:

public class RegistryBeanPostprocessorConfigurer implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.addBeanPostProcessor(getRegistryBeanPostProcessor());
    }
}

context.addBeanFactoryPostProcessor(new RegistryBeanPostProcessorConfigurer());
context.refresh();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top