如何以编程方式将beanPostProcessor添加到ClassPathXmlApplicationContext?

时间:2013-05-08 19:20:50

标签: spring applicationcontext post-processing

有一种方法可以以编程方式将beanPostProcessor添加到ClassPathXmlApplicationContext中吗?

我可以在xml中以声明方式进行,但显然没有办法以编程方式添加。

我的处理器必须做一些事情,比如我的bean是MyInterfaceAware,然后做setMyInterface(...)。

我需要在代码中执行此操作,因为MyInterface实现在代码中实例化,在启动XML时不可用。

我正在使用Spring 3.1.2.RELEASE。

谢谢,

......这就是我正在做的......

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();
}

1 个答案:

答案 0 :(得分:3)

尝试使用context.getBeanFactory().addBeanPostProcessor(beanPostProcessor)

修改

您还可以使用BeanFactoryPostProcessor

public class RegistryBeanPostprocessorConfigurer implements BeanFactoryPostProcessor {

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

context.addBeanFactoryPostProcessor(new RegistryBeanPostProcessorConfigurer());
context.refresh();