1. 程式人生 > >Spring AOP原始碼分析(生成代理物件)

Spring AOP原始碼分析(生成代理物件)

AOP基本概述

Advice(通知)

BeforeAdvice

package org.springframework.aop;

import java.lang.reflect.Method;

public interface MethodBeforeAdvice extends BeforeAdvice {

    void before(Method method, Object[] args, Object target) throws Throwable;

}

before是回撥方法,在Advice中配置了目標方法後,會在呼叫目標方法時被回撥。

引數:
method:目標方法
args:目標方法的輸入引數
target:目標物件

AfterReturningAdvice

package org.springframework.aop;

import java.lang.reflect.Method;

public interface AfterReturningAdvice extends AfterAdvice {
    void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable;

}

在目標方法呼叫結束並正常返回時,介面被回撥

ThrowsAdvice

public interface ThrowsAdvice extends AfterAdvice {

}

丟擲異常時被回撥,AOP使用反射實現(方法名叫AfterThrowing?)

PointCut(切入點)

public interface Pointcut {

    ClassFilter getClassFilter();

    MethodMatcher getMethodMatcher();

    Pointcut TRUE = TruePointcut.INSTANCE;
}

這裡寫圖片描述

PointCut是通過MethodMatcher 進行切入點方法匹配的,判斷是否需要對當前方法進行增強處理。

通過JdkRegexpMethodPointcut理解MethodMatcher:
在JdkRegexpMethodPointcut的基類StaticMethodMatcherPointcut中設定MethodMatcher為StaticMethodMatcherPointcut(StaticMethodMatcher)

public abstract class StaticMethodMatcherPointcut extends StaticMethodMatcher implements Pointcut {
    @Override
    public final MethodMatcher getMethodMatcher() {
        return this;
    }
}

在JdkRegexpMethodPointcut中通過正則表示式匹配需要增強的方法:

protected boolean matches(String pattern, int patternIndex) {
    Matcher matcher = this.compiledPatterns[patternIndex].matcher(pattern);
    return matcher.matches();
}

在NameMatchMethodPointcut中通過方法名進行方法的匹配:

@Override
public boolean matches(Method method, Class<?> targetClass) {
    for (String mappedName : this.mappedNames) {
        if (mappedName.equals(method.getName()) || isMatch(method.getName(), mappedName)) {
            return true;
        }
    }
    return false;
}

protected boolean isMatch(String methodName, String mappedName) {
    return PatternMatchUtils.simpleMatch(mappedName, methodName);
}

Advisor(通知器)

通知器負責把切入點和增強處理接合起來。
在切點處決定使用哪個通知

AOP設計與實現

JVM動態代理

JDK和CGLIB都是用動態代理實現的

AopProxy代理物件

Spring中,是通過ProxyFactoryBean來完成代理物件的生成的

這裡寫圖片描述

ProxyConfig

資料基類,為ProxyFactoryBean這樣的子類提供配置屬性。

AdvisedSupport

AOP對通知和通知器的操作,對不同的AOP代理的生成都是一樣的。對於具體生代理類,由AdvisedSupport的子類來做。

ProxyCreatorSupport

子類建立AOP代理類的輔助

ProxyFactoryBean

IOC容器中宣告式配置,生成代理類

ProxyFactory

程式設計式使用,生成代理類

AspectJProxyFactory

需要使用AspectJ功能的AOP應用,這個起到整合Spring和AspectJ的作用

具體AOP代理物件的生成是由ProxyFactoryBean、ProxyFactory、AspectJProxyFactory完成的。

如何配置ProxyFactory?

<bean id="testAdvisor" class="com.abc.TestAdvisor" />
<!-- 通知器,實現了目標物件需要增強的切面行為,也就是通知 -->
<!-- 這裡我理解的是被代理的bean的scope如果是prototype,那麼這個代理Bean就是prototype -->
<bean id="testAop" class="org.springframework.aop.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <value>com.test.AbcInterface</value>
    </property>
    <property name="target">
        <!-- 目標物件 -->
        <bean class="com.abc.TestTarget" />
    </property>
    <property name="interceptorNames">
        <!-- 需要攔截的方法介面,通知器 -->
        <list>
            <value>
                testAdvisor
            </value>
        </list>
    </property>
</bean>

代理物件生成過程總覽

以singleTon為例:
這裡寫圖片描述

代理物件獲取入口:

ProxyFactoryBean的getObject

AopProxy生成過程:
這裡寫圖片描述

ProxyFactoryBean的getObject獲取代理物件

@Override
public Object getObject() throws BeansException {
    //初始化通知器鏈,為代理物件配置通知器鏈。
    initializeAdvisorChain();
    //區分SingleTon和ProtoType,生成對應的Proxy
    if (isSingleton()) {
        // 只有SingleTon的Bean才會一開始就初始化,ProtoType的只有在請求的時候才會初始化,代理也一樣
        return getSingletonInstance();
    } else {
        if (this.targetName == null) {
            logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " +
                    "Enable prototype proxies by setting the 'targetName' property.");
        }
        return newPrototypeInstance();
    }
}

關於initializeAdvisorChain

ProxyFactoryBean的initializeAdvisorChain

這個初始化過程有一個標誌位advisorChainInitialized,這個標誌用來表示通知器鏈是否已經初始化。

這個就是通知器鏈,在AdvisorSupport中:

private List<Advisor> advisors = new LinkedList<Advisor>();

如果已經初始化,那麼這裡不會再初始化,直接返回。初始化只是在應用第一次通過ProxyFactoryBean獲取代理物件的時候。

完成這個初始化之後,接著會讀取配置中出現的所有通知器(把通知器的名字交給容器的getBean,IOC容器的回撥獲取通知器),把通知器加入攔截器鏈(addAdvisoronChainCreation實現)。

private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {
    if (this.advisorChainInitialized) {
        return;
    }

    if (!ObjectUtils.isEmpty(this.interceptorNames)) {
        if (this.beanFactory == null) {
            throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
                    "- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
        }

        // Globals can't be last unless we specified a targetSource using the property...
        if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) &&
                this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {
            throw new AopConfigException("Target required after globals");
        }

        // Materialize interceptor chain from bean names.
        for (String name : this.interceptorNames) {
            if (logger.isTraceEnabled()) {
                logger.trace("Configuring advisor or advice '" + name + "'");
            }

            if (name.endsWith(GLOBAL_SUFFIX)) {
                if (!(this.beanFactory instanceof ListableBeanFactory)) {
                    throw new AopConfigException(
                            "Can only use global advisors or interceptors with a ListableBeanFactory");
                }
                addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
                        name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
            }

            else {
                // If we get here, we need to add a named interceptor.
                // We must check if it's a singleton or prototype.
                Object advice;
                if (this.singleton || this.beanFactory.isSingleton(name)) {
                    // Add the real Advisor/Advice to the chain.
                    advice = this.beanFactory.getBean(name);
                }
                else {
                    // It's a prototype Advice or Advisor: replace with a prototype.
                    // Avoid unnecessary creation of prototype bean just for advisor chain initialization.
                    advice = new PrototypePlaceholderAdvisor(name);
                }
                addAdvisorOnChainCreation(advice, name);
            }
        }
    }

    this.advisorChainInitialized = true;
}

生成單件代理物件

ProxyFactoryBean的getSingletonInstance
private synchronized Object getSingletonInstance() {
    if (this.singletonInstance == null) {
        //這裡會呼叫getBean,獲取被代理物件
        this.targetSource = freshTargetSource();
        if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
            // 根據 AOP 框架判斷需要代理的介面 
            Class<?> targetClass = getTargetClass();
            if (targetClass == null) {
                throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
            }
            //這裡是設定代理物件的介面
            setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
        }
        // Initialize the shared singleton instance.
        super.setFrozen(this.freezeProxy);
        //這裡方法會使用ProxyFactory生成需要的Proxy
        this.singletonInstance = getProxy(createAopProxy());
    }
    return this.singletonInstance;
}

//通過createAopProxy返回的AopProxy來得到代理物件
protected Object getProxy(AopProxy aopProxy) {
    return aopProxy.getProxy(this.proxyClassLoader);
}
ProxyFactoryBean的freshTargetSource
private TargetSource freshTargetSource() {
    if (this.targetName == null) {
        if (logger.isTraceEnabled()) {
            logger.trace("Not refreshing target: Bean name not specified in 'interceptorNames'.");
        }
        return this.targetSource;
    }
    else {
        if (this.beanFactory == null) {
            throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
                    "- cannot resolve target with name '" + this.targetName + "'");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Refreshing target with name '" + this.targetName + "'");
        }
        Object target = this.beanFactory.getBean(this.targetName);
        return (target instanceof TargetSource ? (TargetSource) target : new SingletonTargetSource(target));
    }
}

具體代理物件的生成,是在ProxyFactoryBean的基類AdvisedSupport的實現中藉助AopProxyFactory完成。

在ProxyCreatorSupport中,AopProxy是通過AopProxyFactory生成的,需要生成的代理物件資訊封裝在AdvisedSupport中,這個物件也是createAopProxy的輸入引數(this):

ProxyCreatorSupport的createAopProxy
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    //通過AopProxyFactory取得AopProxy,AopProxyFactory是在初始化函式中定義的,使用的是DefaultAopProxyFactory
    return getAopProxyFactory().createAopProxy(this);
}

現在問題轉換為DefaultAopProxyFactory如何生成AopProxy了,這裡有兩種方式,JdkDynamicAopProxy和CglibProxyFactory

DefaultAopProxyFactory的createAopProxy

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            //獲取配置的目標物件
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
            //如果沒有目標物件,丟擲異常,提醒AOP應用提供正確的目標配置
                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);
            }
            //由於CGLIB是一個第三方類庫,所以需要在CLASSPATH中配置
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }
}
JdkDynamicAopProxy 生成AopProxy代理物件:
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
    @Override
    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);

        //JdkDynamicAopProxy 需要實現InvocationHandler這裡才能傳this
        findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //...代理的回撥方法,invoke
    //也可以理解為攔截方法

    }
}
CglibAopProxy生成AopProxy代理物件:
@Override
public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    }

    try {
        Class<?> rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

        Class<?> proxySuperClass = rootClass;
        if (ClassUtils.isCglibProxyClass(rootClass)) {
            proxySuperClass = rootClass.getSuperclass();
            Class<?>[] additionalInterfaces = rootClass.getInterfaces();
            for (Class<?> additionalInterface : additionalInterfaces) {
                this.advised.addInterface(additionalInterface);
            }
        }

        // Validate the class, writing log messages as necessary.
        validateClassIfNecessary(proxySuperClass, classLoader);

        // Configure CGLIB Enhancer...
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader &&
                    ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));

        Callback[] callbacks = getCallbacks(rootClass);
        Class<?>[] types = new Class<?>[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        // fixedInterceptorMap only populated at this point, after getCallbacks call above
        enhancer.setCallbackFilter(new ProxyCallbackFilter(
                this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
        enhancer.setCallbackTypes(types);

        // Generate the proxy class and create a proxy instance.
        return createProxyClassAndInstance(enhancer, callbacks);
    }
    catch (CodeGenerationException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                this.advised.getTargetClass() + "]: " +
                "Common causes of this problem include using a final class or a non-visible class",
                ex);
    }
    catch (IllegalArgumentException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                this.advised.getTargetClass() + "]: " +
                "Common causes of this problem include using a final class or a non-visible class",
                ex);
    }
    catch (Exception ex) {
        // TargetSource.getTarget() failed
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

攔截方法寫在內部類裡了(在上面getCallbacks涉及到):

private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {

    private final AdvisedSupport advised;

    public DynamicAdvisedInterceptor(AdvisedSupport advised) {
        this.advised = advised;
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object oldProxy = null;
        boolean setProxyContext = false;
        Class<?> targetClass = null;
        Object target = null;
        try {
            if (this.advised.exposeProxy) {
                // Make invocation available if necessary.
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }
            // May be null. Get as late as possible to minimize the time we
            // "own" the target, in case it comes from a pool...
            target = getTarget();
            if (target != null) {
                targetClass = target.getClass();
            }
            // 從advised中取得配置好的通知
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
            Object retVal;
            // Check whether we only have one InvokerInterceptor: that is,
            // no real advice, but just reflective invocation of the target.
            // 如果沒有AOP通知配置,那麼直接呼叫target物件的呼叫方法
            if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
                // We can skip creating a MethodInvocation: just invoke the target directly.
                // Note that the final invoker must be an InvokerInterceptor, so we know
                // it does nothing but a reflective operation on the target, and no hot
                // swapping or fancy proxying.
                Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                retVal = methodProxy.invoke(target, argsToUse);
            }
            else {
                // We need to create a method invocation...
                // 通過CglibMethodInvocation來啟動通知
                retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
            }
            retVal = processReturnType(proxy, target, method, retVal);
            return retVal;
        }
        finally {
            if (target != null) {
                releaseTarget(target);
            }
            if (setProxyContext) {
                // Restore old proxy.
                AopContext.setCurrentProxy(oldProxy);
            }
        }
    }

    @Override
    public boolean equals(Object other) {
        return (this == other ||
                (other instanceof DynamicAdvisedInterceptor &&
                        this.advised.equals(((DynamicAdvisedInterceptor) other).advised)));
    }

    /**
     * CGLIB uses this to drive proxy creation.
     */
    @Override
    public int hashCode() {
        return this.advised.hashCode();
    }

    protected Object getTarget() throws Exception {
        return this.advised.getTargetSource().getTarget();
    }

    protected void releaseTarget(Object target) throws Exception {
        this.advised.getTargetSource().releaseTarget(target);
    }
}

可以把AOP的實現部分堪稱有基礎設施準備和AOP執行輔助這兩部分組成。

這裡的AOPProxy代理物件的生成,可以看作是一個靜態的AOP基礎設施的建立過程。通過這個準備過程,把代理物件、攔截器這些待呼叫的部分都準備好,等待著AOP執行過程中對這些基礎設施的使用。

對於應用觸發的AOP應用,會涉及AOP框架的執行和對AOP基礎設施的使用。

這些動態的執行部分,是從攔截器回撥入口開始的。