【Spring源碼分析】AOP源碼解析(上篇)

前言

爲了探究AOP實現原理,先定義一個Dao接口:java

public interface Dao {
    
    public void select();

    public void insert();
    
}

Dao接口的實現類DaoImpl:node

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中,這扮演的是橫切關注點的角色:spring

public class TimeHandler {

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

定義一個XML文件aop.xml:express

<?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" />

    <aop:config proxy-target-class="true">
        <aop:aspect id="time" ref="timeHandler">
            <aop:pointcut id="addAllMethod" expression="execution(* org.xrq.action.aop.Dao.*(..))" />
            <aop:before method="printTime" pointcut-ref="addAllMethod" />
            <aop:after method="printTime" pointcut-ref="addAllMethod" />
        </aop:aspect>
    </aop:config>
    
</beans>

寫一段測試代碼TestAop.java:dom

public class TestAop {

    @Test
    public void testAop() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring/aop.xml");
        
        Dao dao = (Dao)ac.getBean("daoImpl");
        dao.select();
    }
    
}

代碼運行結果就不看了,有了以上的內容,咱們就能夠根據這些跟一下代碼,看看Spring究竟是如何實現AOP的。ide

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

有不少朋友不肯意去看AOP源碼的一個很大緣由是由於找不到AOP源碼實現的入口在哪裏,這個確實是。不過咱們能夠看一下上面的測試代碼,就普通Bean也好、AOP也好,最終都是經過getBean方法獲取到Bean並調用方法的,getBean以後的對象已經先後都打印了TimeHandler類printTime()方法裏面的內容,能夠想見它們已是被Spring容器處理過了。工具

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

  1. 加載Bean定義的時候應該有過特殊的處理
  2. 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。可是在遇到後面的aop:config標籤的時候就不同了,aop:config並非默認的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。this

首先第2行從aop:config這個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方法,解析aop:config下的內容了。

AOP Bean定義加載----根據織入方式將aop:beforeaop:after轉換成名爲adviceDef的RootBeanDefinition

上面通過分析,已經找到了Spring是經過AopNamespaceHandler處理的AOP,那麼接着進入AopNamespaceHandler的parse方法源代碼:

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

首先獲取具體的Parser,由於當前節點是aop:config,上一部分最後有列,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進行代理以及是否暴露最終的代理。

aop:config下的節點爲aop:aspect,想見必然是執行第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(
                                "<aspect> 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循環只用來處理aop:aspect標籤下的aop:beforeaop:afteraop:after-returning、<aop:after-throwing method="">、<aop:around method="">這五個標籤的。

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

private AbstractBeanDefinition parseAdvice(
        String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext,
        List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
 5     try {
        this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement)));
 8         // 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);
14         // 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();
    }
}

方法主要作了三件事:

  1. 根據織入方式(before、after這些)建立RootBeanDefinition,名爲adviceDef即advice定義
  2. 將上一步建立的RootBeanDefinition寫入一個新的RootBeanDefinition,構造一個新的對象,名爲advisorDefinition,即advisor定義
  3. 將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方法剩餘邏輯沒什麼,就是判斷一下標籤裏面的屬性並設置一下相應的值而已,至此aop:beforeaop:after兩個標籤對應的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行的代碼是用於判斷aop:aspect標籤中有沒有"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#一、org.springframework.aop.aspectj.AspectJPointcutAdvisor#2這樣下去。

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

AOP Bean定義加載----AopNamespaceHandler處理aop:pointcut流程

回到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();
    }
}

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

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

第9行的代碼拿到全部aop:aspect下的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行的代碼獲取aop:pointcut標籤下的"id"屬性與"expression"屬性。

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

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

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

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

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

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

最後回頭來一下第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;
}

關鍵就是注意一下兩點:

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

相關文章
相關標籤/搜索