Spring BeanPostProcessor&BeanFactoryPostPrcoessor

一.BeanPostProcessor

在Bean初始化前后,由Spring回调,可以在Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理。

public interface BeanPostProcessor {

     /**
     *  在任何初始化代码(比如配置文件中的init-method)调用之前调用。
     */
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    /**
     *  实例化之后进行处理
     */
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

注意:
1. ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean。并把他们注册为后置处理器,然后在容器创建bean的适当时候调用它。因此部署一个后置处理器同部署其他bean并没有什么区别。

        <bean class="TestBeanPostProcessor" />

2.而使用BeanFactory实现的时候,bean后置处理器必须通过代码显式的去注册,在IOC容器集成体系中ConfingurableBeanFactory接口中定义了注册方法。

        TestBeanPostPrcessor beanPostProcessor = new TestBeanPostPrcessor();
        Resource resource = new FileSystemResource("applicationContext.xml");
        ConfigurableBeanFactory factory = new XmlBeanFactory(resource);
        factory.addBeanPostProcessor(beanPostProcessor);
        factory.getBean("logic");

二.BeanFactoryPostProcessor

  与BeanPostProcessor接口类似,可以对bean的定义进行处理

public interface BeanFactoryPostProcessor {

    /**
     * 在所有bean的配置加载完毕,任何一个bean创建之前调用
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

  典型的BeanFactoryPostProcessor是PropertyPlaceholderConfigurer,它间接继承了BeanFactory,在bean工厂加载了所有bean的配置之后,spring就会调用postProcessBeanFactory方法,去读取所有的.property文件并将其中的配置转化为对相应的类型告知BeanFactory。


    /**
     *   PropertyPlaceholderConfigurer-->PlaceholderConfigurerSupport-->
     *   PropertyResourceConfigurer-->BeanFactoryPostProcessor
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            Properties mergedProps = mergeProperties();

            // Convert the merged properties, if necessary.
            convertProperties(mergedProps);

            // Let the subclass process the properties.
            processProperties(beanFactory, mergedProps);
        }
        catch (IOException ex) {
            throw new BeanInitializationException("Could not load properties", ex);
        }
    }

  只有通过ApplicationContext管理bean时BeanFactoryPostProcessor才会有作用,ApplicationContext会自动检测在配置文件中实现了BeanFactoryPostProcessor接口的所有bean,并存放在beanFactoryPostProcessors中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值