Spring源碼剖析7:AOP實現原理詳解

本文轉自五月的倉頡 https://www.cnblogs.com/xrq730

本系列文章將整理到我在GitHub上的《Java面試指南》倉庫,更多精彩內容請到我的倉庫裏查看

https://github.com/h2pl/Java-Tutorial

喜歡的話麻煩點下Star哈

文章將同步到我的個人博客:

www.how2playlife.com

本文是微信公衆號【Java技術江湖】的《Spring和SpringMVC源碼分析》其中一篇,本文部分內容來源於網絡,爲了把本文主題講得清晰透徹,也整合了很多我認爲不錯的技術博客內容,引用其中了一些比較好的博客文章,如有侵權,請聯繫作者。

該系列博文會告訴你如何從spring基礎入手,一步步地學習spring基礎和springmvc的框架知識,並上手進行項目實戰,spring框架是每一個Java工程師必須要學習和理解的知識點,進一步來說,你還需要掌握spring甚至是springmvc的源碼以及實現原理,才能更完整地瞭解整個spring技術體系,形成自己的知識框架。

後續還會有springboot和springcloud的技術專題,陸續爲大家帶來,敬請期待。

爲了更好地總結和檢驗你的學習成果,本系列文章也會提供部分知識點對應的面試題以及參考答案。

如果對本系列文章有什麼建議,或者是有什麼疑問的話,也可以關注公衆號【Java技術江湖】聯繫作者,歡迎你參與本系列博文的創作和修訂。

<!-- more -->

前言

前面寫了六篇文章詳細地分析了Spring Bean加載流程,這部分完了之後就要進入一個比較困難的部分了,就是AOP的實現原理分析。爲了探究AOP實現原理,首先定義幾個類,一個Dao接口:

public interface Dao {
public void select();
public void insert();
}
Dao接口的實現類DaoImpl:

public class DaoImpl implements Dao {

    @Override
    public void select() {
        System.out.println("Enter DaoImpl.select()");
    }

    @Override
    public void insert() {
        System.out.println("Enter DaoImpl.insert()");
    }

}

定義一個TimeHandler,用於方法調用前後打印時間,在AOP中,這扮演的是橫切關注點的角色:

public class TimeHandler {

    public void printTime() {
        System.out.println("CurrentTime:" + System.currentTimeMillis());
    }

}

定義一個XML文件aop.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="daoImpl" class="org.xrq.action.aop.DaoImpl" />
    <bean id="timeHandler" class="org.xrq.action.aop.TimeHandler" />

</beans>

寫一段測試代碼TestAop.java:

public class TestAop {

    @Test
    public void testAop() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring/aop.xml");

        Dao dao = (Dao)ac.getBean("daoImpl");
        dao.select();
    }

}

代碼運行結果就不看了,有了以上的內容,我們就可以根據這些跟一下代碼,看看Spring到底是如何實現AOP的。

AOP實現原理——找到Spring處理AOP的源頭

有很多朋友不願意去看AOP源碼的一個很大原因是因爲找不到AOP源碼實現的入口在哪裏,這個確實是。不過我們可以看一下上面的測試代碼,就普通Bean也好、AOP也好,最終都是通過getBean方法獲取到Bean並調用方法的,getBean之後的對象已經前後都打印了TimeHandler類printTime()方法裏面的內容,可以想見它們已經是被Spring容器處理過了。

既然如此,那無非就兩個地方處理:

加載Bean定義的時候應該有過特殊的處理
getBean的時候應該有過特殊的處理
因此,本文圍繞【1.加載Bean定義的時候應該有過特殊的處理】展開,先找一下到底是哪裏Spring對AOP做了特殊的處理。代碼直接定位到DefaultBeanDefinitionDocumentReader的parseBeanDefinitions方法:

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    if (delegate.isDefaultNamespace(root)) {
        NodeList nl = root.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                Element ele = (Element) node;
                if (delegate.isDefaultNamespace(ele)) {
                    parseDefaultElement(ele, delegate);
                }
                else {
                    delegate.parseCustomElement(ele);
                }
            }
        }
    }
    else {
        delegate.parseCustomElement(root);
    }
}

正常來說,遇到<bean id=”daoImpl”…>、<bean id=”timeHandler”…>這兩個標籤的時候,都會執行第9行的代碼,因爲<bean>標籤是默認的Namespace。但是在遇到後面的標籤的時候就不一樣了,並不是默認的Namespace,因此會執行第12行的代碼,看一下:

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
    String namespaceUri = getNamespaceURI(ele);
    NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
    if (handler == null) {
        error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
        return null;
    }
    return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

因爲之前把整個XML解析爲了org.w3c.dom.Document,org.w3c.dom.Document以樹的形式表示整個XML,具體到每一個節點就是一個Node。

首先第2行從這個Node(參數Element是Node接口的子接口)中拿到Namespace=”http://www.springframework.org/schema/aop“,第3行的代碼根據這個Namespace獲取對應的NamespaceHandler即Namespace處理器,具體到aop這個Namespace的NamespaceHandler是org.springframework.aop.config.AopNamespaceHandler類,也就是第3行代碼獲取到的結果。具體到AopNamespaceHandler裏面,有幾個Parser,是用於具體標籤轉換的,分別爲:

config–>ConfigBeanDefinitionParser
aspectj-autoproxy–>AspectJAutoProxyBeanDefinitionParser
scoped-proxy–>ScopedProxyBeanDefinitionDecorator
spring-configured–>SpringConfiguredBeanDefinitionParser
接着,就是第8行的代碼,利用AopNamespaceHandler的parse方法,解析下的內容了。

解析增強器advisor

AOP Bean定義加載——根據織入方式將、轉換成名爲adviceDef的RootBeanDefinition
上面經過分析,已經找到了Spring是通過AopNamespaceHandler處理的AOP,那麼接着進入AopNamespaceHandler的parse方法源代碼:

public BeanDefinition parse(Element element, ParserContext parserContext) {
    return findParserForElement(element, parserContext).parse(element, parserContext);
}   

首先獲取具體的Parser,因爲當前節點是,上一部分最後有列,config是通過ConfigBeanDefinitionParser來處理的,因此findParserForElement(element, parserContext)這一部分代碼獲取到的是ConfigBeanDefinitionParser,接着看ConfigBeanDefinitionParser的parse方法:

public BeanDefinition parse(Element element, ParserContext parserContext) {
    CompositeComponentDefinition compositeDef =
            new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
    parserContext.pushContainingComponent(compositeDef);

    configureAutoProxyCreator(parserContext, element);

    List<Element> childElts = DomUtils.getChildElements(element);
    for (Element elt: childElts) {
        String localName = parserContext.getDelegate().getLocalName(elt);
        if (POINTCUT.equals(localName)) {
            parsePointcut(elt, parserContext);
        }
        else if (ADVISOR.equals(localName)) {
            parseAdvisor(elt, parserContext);
        }
        else if (ASPECT.equals(localName)) {
            parseAspect(elt, parserContext);
        }
    }

    parserContext.popAndRegisterContainingComponent();
    return null;
}

重點先提一下第6行的代碼,該行代碼的具體實現不跟了但它非常重要,configureAutoProxyCreator方法的作用我用幾句話說一下:

向Spring容器註冊了一個BeanName爲org.springframework.aop.config.internalAutoProxyCreator的Bean定義,可以自定義也可以使用Spring提供的(根據優先級來)
Spring默認提供的是org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator,這個類是AOP的核心類,留在下篇講解
在這個方法裏面也會根據配置proxy-target-class和expose-proxy,設置是否使用CGLIB進行代理以及是否暴露最終的代理。
下的節點爲,想見必然是執行第18行的代碼parseAspect,跟進去:

private void parseAspect(Element aspectElement, ParserContext parserContext) {
    String aspectId = aspectElement.getAttribute(ID);
    String aspectName = aspectElement.getAttribute(REF);

    try {
        this.parseState.push(new AspectEntry(aspectId, aspectName));
        List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();
        List<BeanReference> beanReferences = new ArrayList<BeanReference>();

        List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS);
        for (int i = METHOD_INDEX; i < declareParents.size(); i++) {
            Element declareParentsElement = declareParents.get(i);
            beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext));
        }

        // We have to parse "advice" and all the advice kinds in one loop, to get the
        // ordering semantics right.
        NodeList nodeList = aspectElement.getChildNodes();
        boolean adviceFoundAlready = false;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (isAdviceNode(node, parserContext)) {
                if (!adviceFoundAlready) {
                    adviceFoundAlready = true;
                    if (!StringUtils.hasText(aspectName)) {
                        parserContext.getReaderContext().error(
                                " tag needs aspect bean reference via 'ref' attribute when declaring advices.",
                                aspectElement, this.parseState.snapshot());
                        return;
                    }
                    beanReferences.add(new RuntimeBeanReference(aspectName));
                }
                AbstractBeanDefinition advisorDefinition = parseAdvice(
                        aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences);
                beanDefinitions.add(advisorDefinition);
            }
        }

        AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition(
                aspectElement, aspectId, beanDefinitions, beanReferences, parserContext);
        parserContext.pushContainingComponent(aspectComponentDefinition);

        List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT);
        for (Element pointcutElement : pointcuts) {
            parsePointcut(pointcutElement, parserContext);
        }

        parserContext.popAndRegisterContainingComponent();
    }
    finally {
        this.parseState.pop();
    }
}

從第20行~第37行的循環開始關注這個方法。這個for循環有一個關鍵的判斷就是第22行的ifAdviceNode判斷,看下ifAdviceNode方法做了什麼:

private boolean isAdviceNode(Node aNode, ParserContext parserContext) {
    if (!(aNode instanceof Element)) {
        return false;
    }
    else {
        String name = parserContext.getDelegate().getLocalName(aNode);
        return (BEFORE.equals(name) || AFTER.equals(name) || AFTER_RETURNING_ELEMENT.equals(name) ||
                AFTER_THROWING_ELEMENT.equals(name) || AROUND.equals(name));
    }
}

即這個for循環只用來處理標籤下的、、、、這五個標籤的。

接着,如果是上述五種標籤之一,那麼進入第33行~第34行的parseAdvice方法:

private AbstractBeanDefinition parseAdvice(
    String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext,
    List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
    try {
        this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement)));
        // create the method factory bean
        RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class);
        methodDefinition.getPropertyValues().add("targetBeanName", aspectName);
        methodDefinition.getPropertyValues().add("methodName", adviceElement.getAttribute("method"));
        methodDefinition.setSynthetic(true);
        // create instance factory definition
        RootBeanDefinition aspectFactoryDef =
        new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class);
        aspectFactoryDef.getPropertyValues().add("aspectBeanName", aspectName);
        aspectFactoryDef.setSynthetic(true);

        // register the pointcut
        AbstractBeanDefinition adviceDef = createAdviceDefinition(
            adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef,
            beanDefinitions, beanReferences);

        // configure the advisor
        RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class);
        advisorDefinition.setSource(parserContext.extractSource(adviceElement));
        advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef);
        if (aspectElement.hasAttribute(ORDER_PROPERTY)) {
            advisorDefinition.getPropertyValues().add(
                ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY));
        }

        // register the final advisor
        parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition);

        return advisorDefinition;
    }
    finally {
        this.parseState.pop();
    }
}

方法主要做了三件事:

根據織入方式(before、after這些)創建RootBeanDefinition,名爲adviceDef即advice定義

將上一步創建的RootBeanDefinition寫入一個新的RootBeanDefinition,構造一個新的對象,名爲advisorDefinition,即advisor定義
將advisorDefinition註冊到DefaultListableBeanFactory中
下面來看做的第一件事createAdviceDefinition方法定義:

private AbstractBeanDefinition createAdviceDefinition(
        Element adviceElement, ParserContext parserContext, String aspectName, int order,
        RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef,
        List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {

    RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext));
    adviceDefinition.setSource(parserContext.extractSource(adviceElement));
        adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName);
    adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order);

    if (adviceElement.hasAttribute(RETURNING)) {
        adviceDefinition.getPropertyValues().add(
                RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING));
    }
    if (adviceElement.hasAttribute(THROWING)) {
        adviceDefinition.getPropertyValues().add(
                THROWING_PROPERTY, adviceElement.getAttribute(THROWING));
    }
    if (adviceElement.hasAttribute(ARG_NAMES)) {
        adviceDefinition.getPropertyValues().add(
                ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES));
    }

    ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues();
    cav.addIndexedArgumentValue(METHOD_INDEX, methodDef);

    Object pointcut = parsePointcutProperty(adviceElement, parserContext);
    if (pointcut instanceof BeanDefinition) {
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut);
        beanDefinitions.add((BeanDefinition) pointcut);
    }
    else if (pointcut instanceof String) {
        RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut);
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef);
        beanReferences.add(pointcutRef);
    }

    cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef);

    return adviceDefinition;
}

首先可以看到,創建的AbstractBeanDefinition實例是RootBeanDefinition,這和普通Bean創建的實例爲GenericBeanDefinition不同。然後進入第6行的getAdviceClass方法看一下:

private Class getAdviceClass(Element adviceElement, ParserContext parserContext) {
    String elementName = parserContext.getDelegate().getLocalName(adviceElement);
    if (BEFORE.equals(elementName)) {
        return AspectJMethodBeforeAdvice.class;
    }
    else if (AFTER.equals(elementName)) {
        return AspectJAfterAdvice.class;
    }
    else if (AFTER_RETURNING_ELEMENT.equals(elementName)) {
        return AspectJAfterReturningAdvice.class;
    }
    else if (AFTER_THROWING_ELEMENT.equals(elementName)) {
        return AspectJAfterThrowingAdvice.class;
    }
    else if (AROUND.equals(elementName)) {
        return AspectJAroundAdvice.class;
    }
    else {
        throw new IllegalArgumentException("Unknown advice kind [" + elementName + "].");
    }
}

既然創建Bean定義,必然該Bean定義中要對應一個具體的Class,不同的切入方式對應不同的Class:

before對應AspectJMethodBeforeAdvice
After對應AspectJAfterAdvice
after-returning對應AspectJAfterReturningAdvice
after-throwing對應AspectJAfterThrowingAdvice
around對應AspectJAroundAdvice

createAdviceDefinition方法剩餘邏輯沒什麼,就是判斷一下標籤裏面的屬性並設置一下相應的值而已,至此、兩個標籤對應的AbstractBeanDefinition就創建出來了。

AOP Bean定義加載——將名爲adviceDef的RootBeanDefinition轉換成名爲advisorDefinition的RootBeanDefinition
下面我們看一下第二步的操作,將名爲adviceDef的RootBeanD轉換成名爲advisorDefinition的RootBeanDefinition,跟一下上面一部分ConfigBeanDefinitionParser類parseAdvice方法的第26行~32行的代碼:

RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class);
advisorDefinition.setSource(parserContext.extractSource(adviceElement));
advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef);
if (aspectElement.hasAttribute(ORDER_PROPERTY)) {
    advisorDefinition.getPropertyValues().add(
            ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY));
}

這裏相當於將上一步生成的RootBeanDefinition包裝了一下,new一個新的RootBeanDefinition出來,Class類型是org.springframework.aop.aspectj.AspectJPointcutAdvisor。

第4行~第7行的代碼是用於判斷標籤中有沒有”order”屬性的,有就設置一下,”order”屬性是用來控制切入方法優先級的。

AOP Bean定義加載——將BeanDefinition註冊到DefaultListableBeanFactory中

最後一步就是將BeanDefinition註冊到DefaultListableBeanFactory中了,代碼就是前面ConfigBeanDefinitionParser的parseAdvice方法的最後一部分了:

// register the final advisor
parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition);
...
跟一下registerWithGeneratedName方法的實現:

public String registerWithGeneratedName(BeanDefinition beanDefinition) {
String generatedName = generateBeanName(beanDefinition);
getRegistry().registerBeanDefinition(generatedName, beanDefinition);
return generatedName;
}


第2行獲取註冊的名字BeanName,和<bean>的註冊差不多,使用的是Class全路徑+”#”+全局計數器的方式,其中的Class全路徑爲org.springframework.aop.aspectj.AspectJPointcutAdvisor,依次類推,每一個BeanName應當爲org.springframework.aop.aspectj.AspectJPointcutAdvisor#0、org.springframework.aop.aspectj.AspectJPointcutAdvisor#1、org.springframework.aop.aspectj.AspectJPointcutAdvisor#2這樣下去。

第3行向DefaultListableBeanFactory中註冊,BeanName已經有了,剩下的就是Bean定義,Bean定義的解析流程之前已經看過了,就不說了。

解析切面的過程

AOP Bean定義加載——AopNamespaceHandler處理流程
回到ConfigBeanDefinitionParser的parseAspect方法:

private void parseAspect(Element aspectElement, ParserContext parserContext) {

        ...  

        AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition(
                aspectElement, aspectId, beanDefinitions, beanReferences, parserContext);
        parserContext.pushContainingComponent(aspectComponentDefinition);

        List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT);
        for (Element pointcutElement : pointcuts) {
            parsePointcut(pointcutElement, parserContext);
        }

        parserContext.popAndRegisterContainingComponent();
    }
    finally {
        this.parseState.pop();
    }
}

省略號部分表示是解析的是、這種標籤,上部分已經說過了,就不說了,下面看一下解析部分的源碼。

第5行~第7行的代碼構建了一個Aspect標籤組件定義,並將Apsect標籤組件定義推到ParseContext即解析工具上下文中,這部分代碼不是關鍵。

第9行的代碼拿到所有下的pointcut標籤,進行遍歷,由parsePointcut方法進行處理:

private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) {
    String id = pointcutElement.getAttribute(ID);
    String expression = pointcutElement.getAttribute(EXPRESSION);

    AbstractBeanDefinition pointcutDefinition = null;

    try {
        this.parseState.push(new PointcutEntry(id));
        pointcutDefinition = createPointcutDefinition(expression);
        pointcutDefinition.setSource(parserContext.extractSource(pointcutElement));

        String pointcutBeanName = id;
        if (StringUtils.hasText(pointcutBeanName)) {
            parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition);
        }
        else {
            pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition);
        }

        parserContext.registerComponent(
                new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression));
    }
    finally {
        this.parseState.pop();
    }

    return pointcutDefinition;
}

第2行~第3行的代碼獲取標籤下的”id”屬性與”expression”屬性。

第8行的代碼推送一個PointcutEntry,表示當前Spring上下文正在解析Pointcut標籤。

第9行的代碼創建Pointcut的Bean定義,之後再看,先把其他方法都看一下。

第10行的代碼不管它,最終從NullSourceExtractor的extractSource方法獲取Source,就是個null。

第12行~第18行的代碼用於註冊獲取到的Bean定義,默認pointcutBeanName爲標籤中定義的id屬性:

如果標籤中配置了id屬性就執行的是第13行~第15行的代碼,pointcutBeanName=id
如果標籤中沒有配置id屬性就執行的是第16行~第18行的代碼,和Bean不配置id屬性一樣的規則,pointcutBeanName=org.springframework.aop.aspectj.AspectJExpressionPointcut#序號(從0開始累加)
第20行~第21行的代碼向解析工具上下文中註冊一個Pointcut組件定義

第23行~第25行的代碼,finally塊在標籤解析完畢後,讓之前推送至棧頂的PointcutEntry出棧,表示此次標籤解析完畢。

最後回頭來一下第9行代碼createPointcutDefinition的實現,比較簡單:

protected AbstractBeanDefinition createPointcutDefinition(String expression) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class);
    beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    beanDefinition.setSynthetic(true);
    beanDefinition.getPropertyValues().add(EXPRESSION, expression);
    return beanDefinition;
}

關鍵就是注意一下兩點:

標籤對應解析出來的BeanDefinition是RootBeanDefinition,且RootBenaDefinitoin中的Class是org.springframework.aop.aspectj.AspectJExpressionPointcut
標籤對應的Bean是prototype即原型的
這樣一個流程下來,就解析了標籤中的內容並將之轉換爲RootBeanDefintion存儲在Spring容器中。

AOP爲Bean生成代理的時機分析

上篇文章說了,org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator這個類是Spring提供給開發者的AOP的核心類,就是AspectJAwareAdvisorAutoProxyCreator完成了【類/接口–>代理】的轉換過程,首先我們看一下AspectJAwareAdvisorAutoProxyCreator的層次結構:

這裏最值得注意的一點是最左下角的那個方框,我用幾句話總結一下:

AspectJAwareAdvisorAutoProxyCreator是BeanPostProcessor接口的實現類
postProcessBeforeInitialization方法與postProcessAfterInitialization方法實現在父類AbstractAutoProxyCreator中
postProcessBeforeInitialization方法是一個空實現
邏輯代碼在postProcessAfterInitialization方法中
基於以上的分析,將Bean生成代理的時機已經一目瞭然了:在每個Bean初始化之後,如果需要,調用AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization爲Bean生成代理。

代理對象實例化—-判斷是否爲<bean>生成代理
上文分析了Bean生成代理的時機是在每個Bean初始化之後,下面把代碼定位到Bean初始化之後,先是AbstractAutowireCapableBeanFactory的initializeBean方法進行初始化:

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    }
    else {
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
    invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }

    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

初始化之前是第16行的applyBeanPostProcessorsBeforeInitialization方法,初始化之後即29行的applyBeanPostProcessorsAfterInitialization方法:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

這裏調用每個BeanPostProcessor的postProcessBeforeInitialization方法。按照之前的分析,看一下AbstractAutoProxyCreator的postProcessAfterInitialization方法實現:

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean != null) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        if (!this.earlyProxyReferences.contains(cacheKey)) {
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

跟一下第5行的方法wrapIfNecessary:

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    if (this.nonAdvisedBeans.contains(cacheKey)) {
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.nonAdvisedBeans.add(cacheKey);
        return bean;
    }

    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.add(cacheKey);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    this.nonAdvisedBeans.add(cacheKey);
    return bean;
}

第2行~第11行是一些不需要生成代理的場景判斷,這裏略過。首先我們要思考的第一個問題是:哪些目標對象需要生成代理?因爲配置文件裏面有很多Bean,肯定不能對每個Bean都生成代理,因此需要一套規則判斷Bean是不是需要生成代理,這套規則就是第14行的代碼getAdvicesAndAdvisorsForBean:

    protected List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) {
        List<Advisor> candidateAdvisors = findCandidateAdvisors();
        List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        extendAdvisors(eligibleAdvisors);
        if (!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = sortAdvisors(eligibleAdvisors);
        }
        return eligibleAdvisors;
    }

顧名思義,方法的意思是爲指定class尋找合適的Advisor。

第2行代碼,尋找候選Advisors,根據上文的配置文件,有兩個候選Advisor,分別是節點下的和這兩個,這兩個在XML解析的時候已經被轉換生成了RootBeanDefinition。

跳過第3行的代碼,先看下第4行的代碼extendAdvisors方法,之後再重點看一下第3行的代碼。第4行的代碼extendAdvisors方法作用是向候選Advisor鏈的開頭(也就是List.get(0)的位置)添加一個org.springframework.aop.support.DefaultPointcutAdvisor。

第3行代碼,根據候選Advisors,尋找可以使用的Advisor,跟一下方法實現:

public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
    if (candidateAdvisors.isEmpty()) {
        return candidateAdvisors;
    }
    List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();
    for (Advisor candidate : candidateAdvisors) {
        if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
            eligibleAdvisors.add(candidate);
        }
    }
    boolean hasIntroductions = !eligibleAdvisors.isEmpty();
    for (Advisor candidate : candidateAdvisors) {
        if (candidate instanceof IntroductionAdvisor) {
            // already processed
            continue;
        }
        if (canApply(candidate, clazz, hasIntroductions)) {
            eligibleAdvisors.add(candidate);
        }
    }
    return eligibleAdvisors;
}

整個方法的主要判斷都圍繞canApply展開方法:

public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
    if (advisor instanceof IntroductionAdvisor) {
        return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
    }
    else if (advisor instanceof PointcutAdvisor) {
        PointcutAdvisor pca = (PointcutAdvisor) advisor;
        return canApply(pca.getPointcut(), targetClass, hasIntroductions);
    }
    else {
        // It doesn't have a pointcut so we assume it applies.
        return true;
    }
}

第一個參數advisor的實際類型是AspectJPointcutAdvisor,它是PointcutAdvisor的子類,因此執行第7行的方法:

public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
    if (!pc.getClassFilter().matches(targetClass)) {
        return false;
    }

    MethodMatcher methodMatcher = pc.getMethodMatcher();
    IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
    if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
        introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
    }

    Set<Class> classes = new HashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
    classes.add(targetClass);
    for (Class<?> clazz : classes) {
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if ((introductionAwareMethodMatcher != null &&
                introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
                    methodMatcher.matches(method, targetClass)) {
                return true;
            }
        }
    }
    return false;
}

這個方法其實就是拿當前Advisor對應的expression做了兩層判斷:

目標類必須滿足expression的匹配規則
目標類中的方法必須滿足expression的匹配規則,當然這裏方法不是全部需要滿足expression的匹配規則,有一個方法滿足即可
如果以上兩條都滿足,那麼容器則會判斷該<bean>滿足條件,需要被生成代理對象,具體方式爲返回一個數組對象,該數組對象中存儲的是<bean>對應的Advisor。

代理對象實例化過程

代理對象實例化—-爲<bean>生成代理代碼上下文梳理
上文分析了爲<bean>生成代理的條件,現在就正式看一下Spring上下文是如何爲<bean>生成代理的。回到AbstractAutoProxyCreator的wrapIfNecessary方法:

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    if (this.nonAdvisedBeans.contains(cacheKey)) {
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.nonAdvisedBeans.add(cacheKey);
        return bean;
    }

    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.add(cacheKey);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    this.nonAdvisedBeans.add(cacheKey);
    return bean;
}

第14行拿到<bean>對應的Advisor數組,第15行判斷只要Advisor數組不爲空,那麼就會通過第17行的代碼爲<bean>創建代理:

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

    ProxyFactory proxyFactory = new ProxyFactory();
    // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
    proxyFactory.copyFrom(this);

    if (!shouldProxyTargetClass(beanClass, beanName)) {
        // Must allow for introductions; can't just set interfaces to
        // the target's interfaces only.
        Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader);
        for (Class<?> targetInterface : targetInterfaces) {
            proxyFactory.addInterface(targetInterface);
        }
    }

    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    for (Advisor advisor : advisors) {
        proxyFactory.addAdvisor(advisor);
    }

    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);

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

    return proxyFactory.getProxy(this.proxyClassLoader);
}

第4行~第6行new出了一個ProxyFactory,Proxy,顧名思義,代理工廠的意思,提供了簡單的方式使用代碼獲取和配置AOP代理。

第8行的代碼做了一個判斷,判斷的內容是這個節點中proxy-target-class=”false”或者proxy-target-class不配置,即不使用CGLIB生成代理。如果滿足條件,進判斷,獲取當前Bean實現的所有接口,講這些接口Class對象都添加到ProxyFactory中。

第17行~第28行的代碼沒什麼看的必要,向ProxyFactory中添加一些參數而已。重點看第30行proxyFactory.getProxy(this.proxyClassLoader)這句:

public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}

實現代碼就一行,但是卻明確告訴我們做了兩件事情:

創建AopProxy接口實現類
通過AopProxy接口的實現類的getProxy方法獲取<bean>對應的代理
就從這兩個點出發,分兩部分分析一下。

代理對象實例化—-創建AopProxy接口實現類
看一下createAopProxy()方法的實現,它位於DefaultAopProxyFactory類中:

protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}

前面的部分沒什麼必要看,直接進入重點即createAopProxy方法:

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    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()) {
            return new JdkDynamicAopProxy(config);
        }
        if (!cglibAvailable) {
            throw new AopConfigException(
                    "Cannot proxy target class because CGLIB2 is not available. " +
                    "Add CGLIB to the class path or specify proxy interfaces.");
        }
        return CglibProxyFactory.createCglibProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}

平時我們說AOP原理三句話就能概括:

對類生成代理使用CGLIB
對接口生成代理使用JDK原生的Proxy
可以通過配置文件指定對接口使用CGLIB生成代理
這三句話的出處就是createAopProxy方法。看到默認是第19行的代碼使用JDK自帶的Proxy生成代理,碰到以下三種情況例外:

ProxyConfig的isOptimize方法爲true,這表示讓Spring自己去優化而不是用戶指定
ProxyConfig的isProxyTargetClass方法爲true,這表示配置了proxy-target-class=”true”
ProxyConfig滿足hasNoUserSuppliedProxyInterfaces方法執行結果爲true,這表示<bean>對象沒有實現任何接口或者實現的接口是SpringProxy接口
在進入第2行的if判斷之後再根據目標<bean>的類型決定返回哪種AopProxy。簡單總結起來就是:

proxy-target-class沒有配置或者proxy-target-class=”false”,返回JdkDynamicAopProxy
proxy-target-class=”true”或者<bean>對象沒有實現任何接口或者只實現了SpringProxy接口,返回Cglib2AopProxy
當然,不管是JdkDynamicAopProxy還是Cglib2AopProxy,AdvisedSupport都是作爲構造函數參數傳入的,裏面存儲了具體的Advisor。

代理對象實例化—-通過getProxy方法獲取<bean>對應的代理
其實代碼已經分析到了JdkDynamicAopProxy和Cglib2AopProxy,剩下的就沒什麼好講的了,無非就是看對這兩種方式生成代理的熟悉程度而已。

Cglib2AopProxy生成代理的代碼就不看了,對Cglib不熟悉的朋友可以看Cglib及其基本使用一文。

JdkDynamicAopProxy生成代理的方式稍微看一下:

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);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

這邊解釋一下第5行和第6行的代碼,第5行代碼的作用是拿到所有要代理的接口,第6行代碼的作用是嘗試尋找這些接口方法裏面有沒有equals方法和hashCode方法,同時都有的話打個標記,尋找結束,equals方法和hashCode方法有特殊處理。

最終通過第7行的Proxy.newProxyInstance方法獲取接口/類對應的代理對象,Proxy是JDK原生支持的生成代理的方式。

代理方法調用原理

前面已經詳細分析了爲接口/類生成代理的原理,生成代理之後就要調用方法了,這裏看一下使用JdkDynamicAopProxy調用方法的原理。

由於JdkDynamicAopProxy本身實現了InvocationHandler接口,因此具體代理前後處理的邏輯在invoke方法中:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MethodInvocation invocation;
    Object oldProxy = null;
    boolean setProxyContext = false;

    TargetSource targetSource = this.advised.targetSource;
    Class targetClass = null;
    Object target = null;

    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        }
        if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        }
        if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }

        Object retVal;

        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 = targetSource.getTarget();
        if (target != null) {
            targetClass = target.getClass();
        }

        // Get the interception chain for this method.
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        if (chain.isEmpty()) {
            // 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.
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
        }
        else {
            // We need to create a method invocation...
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            retVal = invocation.proceed();
        }

        // Massage return value if necessary.
        if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) &&
                !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        }
        return retVal;
    }
    finally {
        if (target != null && !targetSource.isStatic()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

第11行~第18行的代碼,表示equals方法與hashCode方法即使滿足expression規則,也不會爲之產生代理內容,調用的是JdkDynamicAopProxy的equals方法與hashCode方法。至於這兩個方法是什麼作用,可以自己查看一下源代碼。

第19行~第23行的代碼,表示方法所屬的Class是一個接口並且方法所屬的Class是AdvisedSupport的父類或者父接口,直接通過反射調用該方法。

第27行~第30行的代碼,是用於判斷是否將代理暴露出去的,由標籤中的expose-proxy=”true/false”配置。

第41行的代碼,獲取AdvisedSupport中的所有攔截器和動態攔截器列表,用於攔截方法,具體到我們的實際代碼,列表中有三個Object,分別是:

chain.get(0):ExposeInvocationInterceptor,這是一個默認的攔截器,對應的原Advisor爲DefaultPointcutAdvisor
chain.get(1):MethodBeforeAdviceInterceptor,用於在實際方法調用之前的攔截,對應的原Advisor爲AspectJMethodBeforeAdvice
chain.get(2):AspectJAfterAdvice,用於在實際方法調用之後的處理
第45行~第50行的代碼,如果攔截器列表爲空,很正常,因爲某個類/接口下的某個方法可能不滿足expression的匹配規則,因此此時通過反射直接調用該方法。

第51行~第56行的代碼,如果攔截器列表不爲空,按照註釋的意思,需要一個ReflectiveMethodInvocation,並通過proceed方法對原方法進行攔截,proceed方法感興趣的朋友可以去看一下,裏面使用到了遞歸的思想對chain中的Object進行了層層的調用。

CGLIB代理實現

下面我們來看一下CGLIB代理的方式,這裏需要讀者去了解一下CGLIB以及其創建代理的方式:

Spring源碼剖析7:AOP實現原理詳解

Spring源碼剖析7:AOP實現原理詳解

Spring源碼剖析7:AOP實現原理詳解

這裏將攔截器鏈封裝到了DynamicAdvisedInterceptor中,並加入了Callback,DynamicAdvisedInterceptor實現了CGLIB的MethodInterceptor,所以其核心邏輯在intercept方法中:

Spring源碼剖析7:AOP實現原理詳解

這裏我們看到了與JDK動態代理同樣的獲取攔截器鏈的過程,並且CglibMethodInvokcation繼承了我們在JDK動態代理看到的ReflectiveMethodInvocation,但是並沒有重寫其proceed方法,只是重寫了執行目標方法的邏輯,所以整體上是大同小異的。

到這裏,整個Spring 動態AOP的源碼就分析完了,Spring還支持靜態AOP,這裏就不過多贅述了,有興趣的讀者可以查閱相關資料來學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章