【spring原始碼學習】Spring的IOC容器之BeanPostProcessor介面學習

Love Lenka發表於2017-07-19

一:含義作用

==>BeanPostProcessor介面是眾多Spring提供給開發者的bean生命週期內自定義邏輯擴充介面中的一個

 

二:介面定義

package org.springframework.beans.factory.config;

import org.springframework.beans.BeansException;

public interface BeanPostProcessor {

    /**
     *IOC容器中的bean例項化之前執行
     */
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    /**
     *IOC容器中的bean例項化之後執行
     */
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}
View Code

三:自定義例項(在ioc例項化的時候執行,並列印內容。xml配置bean,或用註解註釋,即可生效)

package com.mobile.thinks.manages.study;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor{

    /**
     * IOC容器中bean在被例項化之前執行該方法
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
            Class<?>  cls=bean.getClass();
            System.out.println("sxf  【自定義例項化之前】postProcessBeforeInitialization類路徑==>"+cls);
            System.out.println("sxf  【自定義例項化之前】postProcessBeforeInitialization初始化物件的名字==>"+beanName);
        return bean;
    }

    
    /**
     * IOC容器中bean在被例項化之後執行該方法
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        Class<?>  cls=bean.getClass();
        System.out.println("sxf  【自定義例項化之後】postProcessBeforeInitialization類路徑==>"+cls);
        System.out.println("sxf  【自定義例項化之後】postProcessBeforeInitialization初始化物件的名字==>"+beanName);
        return bean;
    }
    
    

}
View Code

 

四:spring內部例子

【1】org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor 類

==>在postProcessAfterInitialization 方法中,將bean中的方法標註有@Async註解的bean,不返回IOC真實的例項化物件,而是返回一個代理物件(動態代理)。org.springframework.scheduling.annotation.AsyncAnnotationAdvisor作為代理物件的執行增強(切面+增加)

 

【2】org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator 類

==>在postProcessAfterInitialization 方法中對bean進行動態代理。

 

相關文章