spring-aop 3.創(chuàng)建代理對象

1.前言

在上一篇中,我分析了 Spring 是如何為目標 bean 篩選合適的通知器的?,F(xiàn)在通知器選好了,接下來就要通過代理的方式將通知器(Advisor)所持有的通知(Advice)織入到 bean 的某些方法前后。與篩選合適的通知器相比,創(chuàng)建代理對象的過程則要簡單不少,本文所分析的源碼不過100行,相對比較簡單。在接下里的章節(jié)中,我將會首先向大家介紹一些背景知識,然后再去分析源碼。那下面,我們先來了解一下背景知識。

2.代理

2.1proxy-target-class

在 Spring AOP 配置中,proxy-target-class 屬性可影響 Spring 生成的代理對象的類型。以 XML 配置為例,可進行如下配置:

<aop:aspectj-autoproxy proxy-target-class="true"/>
<aop:config proxy-target-class="true">
    <aop:aspect id="xxx" ref="xxxx">
        <!-- 省略 -->
    </aop:aspect>
</aop:config>

如上,默認情況下 proxy-target-class 屬性為 false。當目標 bean 實現(xiàn)了接口時,Spring 會基于 JDK 動態(tài)代理為目標 bean 創(chuàng)建代理對象。若未實現(xiàn)任何接口,Spring 則會通過 CGLIB 創(chuàng)建代理。而當 proxy-target-class 屬性設(shè)為 true 時,則會強制 Spring 通過 CGLIB 的方式創(chuàng)建代理對象,即使目標 bean 實現(xiàn)了接口。

關(guān)于 proxy-target-class 屬性的用途這里就說完了,下面我們來看看兩種不同創(chuàng)建動態(tài)代理的方式。

2.2動態(tài)代理

2.2.1基于 JDK 的動態(tài)代理

基于 JDK 的動態(tài)代理主要是通過 JDK 提供的代理創(chuàng)建類 Proxy 為目標對象創(chuàng)建代理,下面我們來看一下 Proxy 中創(chuàng)建代理的方法聲明。如下:

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)

簡單說一下上面的參數(shù)列表:

loader - 類加載器
interfaces - 目標類所實現(xiàn)的接口列表
h - 用于封裝代理邏輯
JDK 動態(tài)代理對目標類是有一定要求的,即要求目標類必須實現(xiàn)了接口,JDK 動態(tài)代理只能為實現(xiàn)了接口的目標類生成代理對象。至于 InvocationHandler,是一個接口類型,定義了一個 invoke 方法。使用者需要實現(xiàn)該方法,并在其中封裝代理邏輯。

關(guān)于 JDK 動態(tài)代理的介紹,就先說到這。下面我來演示一下 JDK 動態(tài)代理的使用方式,如下:

目標類定義:

public interface UserService {

    void save(User user);

    void update(User user);
}

public class UserServiceImpl implements UserService {

    @Override
    public void save(User user) {
        System.out.println("save user info");
    }

    @Override
    public void update(User user) {
        System.out.println("update user info");
    }
}

代理創(chuàng)建者定義:

public interface ProxyCreator {

    Object getProxy();
}

public class JdkProxyCreator implements ProxyCreator, InvocationHandler {

    private Object target;

    public JdkProxyCreator(Object target) {
        assert target != null;
        Class<?>[] interfaces = target.getClass().getInterfaces();
        if (interfaces.length == 0) {
            throw new IllegalArgumentException("target class don`t implement any interface");
        }
        this.target = target;
    }

    @Override
    public Object getProxy() {
        Class<?> clazz = target.getClass();
        // 生成代理對象
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println(System.currentTimeMillis() + " - " + method.getName() + " method start");
        // 調(diào)用目標方法
        Object retVal = method.invoke(target, args);
        System.out.println(System.currentTimeMillis() + " - " + method.getName() + " method over");

        return retVal;
    }
}

如上,invoke 方法中的代理邏輯主要用于記錄目標方法的調(diào)用時間,和結(jié)束時間。下面寫點測試代碼簡單驗證一下,如下:

public class JdkProxyCreatorTest {

    @Test
    public void getProxy() throws Exception {
        ProxyCreator proxyCreator = new JdkProxyCreator(new UserServiceImpl());
        UserService userService = (UserService) proxyCreator.getProxy();
        
        System.out.println("proxy type = " + userService.getClass());
        System.out.println();
        userService.save(null);
        System.out.println();
        userService.update(null);
    }
}

測試結(jié)果:



如上,從測試結(jié)果中。我們可以看出,我們的代理邏輯正常執(zhí)行了。另外,注意一下 userService 指向?qū)ο蟮念愋?,并非?xyz.coolblog.proxy.UserServiceImpl,而是 com.sun.proxy.$Proxy4。

關(guān)于 JDK 動態(tài)代理,這里先說這么多。下一節(jié),我來演示一下 CGLIB 動態(tài)代理,繼續(xù)往下看吧。

2.2.2基于 CGLIB 的動態(tài)代理

當我們要為未實現(xiàn)接口的類生成代理時,就無法使用 JDK 動態(tài)代理了。那么此類的目標對象生成代理時應(yīng)該怎么辦呢?當然是使用 CGLIB 了。在 CGLIB 中,代理邏輯是封裝在 MethodInterceptor 實現(xiàn)類中的,代理對象則是通過 Enhancer 類的 create 方法進行創(chuàng)建。下面我來演示一下 CGLIB 創(chuàng)建代理對象的過程,如下:

public class Tank59 {

    void run() {
        System.out.println("極速前行中....");
    }

    void shoot() {
        System.out.println("轟...轟...轟...轟...");
    }
}

CGLIB 代理創(chuàng)建者

public class CglibProxyCreator implements ProxyCreator {

    private Object target;

    private MethodInterceptor methodInterceptor;

    public CglibProxyCreator(Object target, MethodInterceptor methodInterceptor) {
        assert (target != null && methodInterceptor != null);
        this.target = target;
        this.methodInterceptor = methodInterceptor;
    }

    @Override
    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        // 設(shè)置代理類的父類
        enhancer.setSuperclass(target.getClass());
        // 設(shè)置代理邏輯
        enhancer.setCallback(methodInterceptor);
        // 創(chuàng)建代理對象
        return enhancer.create();
    }
}

方法攔截器 - 坦克再制造:

public class TankRemanufacture implements MethodInterceptor {

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (method.getName().equals("run")) {
            System.out.println("正在重造59坦克...");
            System.out.println("重造成功,已獲取 ?59改 之 超音速飛行版?");
            System.out.print("已起飛,正在突破音障。");

            methodProxy.invokeSuper(o, objects);

            System.out.println("已擊落黑鳥 SR-71,正在返航...");
            return null;
        }

        return methodProxy.invokeSuper(o, objects);
    }
}

好了,下面開始演示,測試代碼如下:

public class CglibProxyCreatorTest {

    @Test
    public void getProxy() throws Exception {
        ProxyCreator proxyCreator = new CglibProxyCreator(new Tank59(), new TankRemanufacture());
        Tank59 tank59 = (Tank59) proxyCreator.getProxy();
        
        System.out.println("proxy class = " + tank59.getClass() + "\n");
        tank59.run();
        System.out.println();
        System.out.print("射擊測試:");
        tank59.shoot();
    }
}

測試結(jié)果如下:


image.png

3. 源碼

為目標 bean 創(chuàng)建代理對象前,需要先創(chuàng)建 AopProxy 對象,然后再調(diào)用該對象的 getProxy 方法創(chuàng)建實際的代理類。我們先來看看 AopProxy 這個接口的定義,如下

public interface AopProxy {

    /** 創(chuàng)建代理對象 */
    Object getProxy();
    
    Object getProxy(ClassLoader classLoader);
}

在 Spring 中,有兩個類實現(xiàn)了 AopProxy,如下:


image.png

Spring 在為目標 bean 創(chuàng)建代理的過程中,要根據(jù) bean 是否實現(xiàn)接口,以及一些其他配置來決定使用 AopProxy 何種實現(xiàn)類為目標 bean 創(chuàng)建代理對象。下面我們就來看一下代理創(chuàng)建的過程,如下

protected Object createProxy(
        Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {

    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);

    /*
     * 默認配置下,或用戶顯式配置 proxy-target-class = "false" 時,
     * 這里的 proxyFactory.isProxyTargetClass() 也為 false
     */
    if (!proxyFactory.isProxyTargetClass()) {
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        else {
            /*
             * 檢測 beanClass 是否實現(xiàn)了接口,若未實現(xiàn),則將 
             * proxyFactory 的成員變量 proxyTargetClass 設(shè)為 true
             */ 
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }

    // specificInterceptors 中若包含有 Advice,此處將 Advice 轉(zhuǎn)為 Advisor
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);

    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }

    // 創(chuàng)建代理
    return proxyFactory.getProxy(getProxyClassLoader());
}

public Object getProxy(ClassLoader classLoader) {
    // 先創(chuàng)建 AopProxy 實現(xiàn)類對象,然后再調(diào)用 getProxy 為目標 bean 創(chuàng)建代理對象
    return createAopProxy().getProxy(classLoader);
}
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        /*
         * 下面的三個條件簡單分析一下:
         *
         *   條件1:config.isOptimize() - 是否需要優(yōu)化,這個屬性沒怎么用過,
         *         細節(jié)我不是很清楚
         *   條件2:config.isProxyTargetClass() - 檢測 proxyTargetClass 的值,
         *         前面的代碼會設(shè)置這個值
         *   條件3:hasNoUserSuppliedProxyInterfaces(config) 
         *         - 目標 bean 是否實現(xiàn)了接口
         */
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
            // 創(chuàng)建 CGLIB 代理,ObjenesisCglibAopProxy 繼承自 CglibAopProxy
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            // 創(chuàng)建 JDK 動態(tài)代理
            return new JdkDynamicAopProxy(config);
        }
    }
}

如上,DefaultAopProxyFactory 根據(jù)一些條件決定生成什么類型的 AopProxy 實現(xiàn)類對象。生成好 AopProxy 實現(xiàn)類對象后,下面就要為目標 bean 創(chuàng)建代理對象了。這里以 JdkDynamicAopProxy 為例,我們來看一下,該類的 getProxy 方法的邏輯是怎樣的。如下:

public Object getProxy() {
    return getProxy(ClassUtils.getDefaultClassLoader());
}

public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    }
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    
    // 調(diào)用 newProxyInstance 創(chuàng)建代理對象
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

如上,請把目光移至最后一行有效代碼上,會發(fā)現(xiàn) JdkDynamicAopProxy 最終調(diào)用 Proxy.newProxyInstance 方法創(chuàng)建代理對象。到此,創(chuàng)建代理對象的整個過程也就分析完了,不知大家看懂了沒。好了,關(guān)于創(chuàng)建代理的源碼分析,就先說到這里吧。

4.總結(jié)

本篇文章對 Spring AOP 創(chuàng)建代理對象的過程進行了較為詳細的分析,并在分析源碼前介紹了相關(guān)的背景知識??偟膩碚f,本篇文章涉及的技術(shù)點不是很復(fù)雜,相信大家都能看懂。限于個人能力,若文中有錯誤的地方,歡迎大家指出來。好了,本篇文章到此結(jié)束,謝謝閱讀。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容