溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理

發(fā)布時間:2021-12-18 17:36:08 來源:億速云 閱讀:137 作者:柒染 欄目:編程語言

今天就跟大家聊聊有關(guān)如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

前言

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

public interface Dao {
public void select();
public void insert();
}
Dao接口的實現(xiàn)類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,用于方法調(diào)用前后打印時間,在AOP中,這扮演的是橫切關(guān)注點的角色:

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

代碼運(yùn)行結(jié)果就不看了,有了以上的內(nèi)容,我們就可以根據(jù)這些跟一下代碼,看看Spring到底是如何實現(xiàn)AOP的。

AOP實現(xiàn)原理——找到Spring處理AOP的源頭

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

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

加載Bean定義的時候應(yīng)該有過特殊的處理
getBean的時候應(yīng)該有過特殊的處理
因此,本文圍繞【1.加載Bean定義的時候應(yīng)該有過特殊的處理】展開,先找一下到底是哪里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);
    }
}

正常來說,遇到、這兩個標(biāo)簽的時候,都會執(zhí)行第9行的代碼,因為標(biāo)簽是默認(rèn)的Namespace。但是在遇到后面的標(biāo)簽的時候就不一樣了,并不是默認(rèn)的Namespace,因此會執(zhí)行第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,具體到每一個節(jié)點就是一個Node。

首先第2行從這個Node(參數(shù)Element是Node接口的子接口)中拿到Namespace=” http://www.springframework.org/schema/aop“,第3行的代碼根據(jù)這個Namespace獲取對應(yīng)的NamespaceHandler即Namespace處理器,具體到aop這個Namespace的NamespaceHandler是org.springframework.aop.config.AopNamespaceHandler類,也就是第3行代碼獲取到的結(jié)果。具體到AopNamespaceHandler里面,有幾個Parser,是用于具體標(biāo)簽轉(zhuǎn)換的,分別為:

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

解析增強(qiáng)器advisor

AOP Bean定義加載——根據(jù)織入方式將、轉(zhuǎn)換成名為adviceDef的RootBeanDefinition
上面經(jīng)過分析,已經(jīng)找到了Spring是通過AopNamespaceHandler處理的AOP,那么接著進(jìn)入AopNamespaceHandler的parse方法源代碼:

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

首先獲取具體的Parser,因為當(dāng)前節(jié)點是,上一部分最后有列,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行的代碼,該行代碼的具體實現(xiàn)不跟了但它非常重要,configureAutoProxyCreator方法的作用我用幾句話說一下:

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

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行的循環(huán)開始關(guān)注這個方法。這個for循環(huán)有一個關(guān)鍵的判斷就是第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循環(huán)只用來處理標(biāo)簽下的、、、、這五個標(biāo)簽的。

接著,如果是上述五種標(biāo)簽之一,那么進(jìn)入第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();
    }
}

方法主要做了三件事:

根據(jù)織入方式(before、after這些)創(chuàng)建RootBeanDefinition,名為adviceDef即advice定義

將上一步創(chuàng)建的RootBeanDefinition寫入一個新的RootBeanDefinition,構(gòu)造一個新的對象,名為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;
}

首先可以看到,創(chuàng)建的AbstractBeanDefinition實例是RootBeanDefinition,這和普通Bean創(chuàng)建的實例為GenericBeanDefinition不同。然后進(jìn)入第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 + "].");
    }
}

既然創(chuàng)建Bean定義,必然該Bean定義中要對應(yīng)一個具體的Class,不同的切入方式對應(yīng)不同的Class:

before對應(yīng)AspectJMethodBeforeAdvice
After對應(yīng)AspectJAfterAdvice
after-returning對應(yīng)AspectJAfterReturningAdvice
after-throwing對應(yīng)AspectJAfterThrowingAdvice
around對應(yīng)AspectJAroundAdvice

createAdviceDefinition方法剩余邏輯沒什么,就是判斷一下標(biāo)簽里面的屬性并設(shè)置一下相應(yīng)的值而已,至此、兩個標(biāo)簽對應(yīng)的AbstractBeanDefinition就創(chuàng)建出來了。

AOP Bean定義加載——將名為adviceDef的RootBeanDefinition轉(zhuǎn)換成名為advisorDefinition的RootBeanDefinition
下面我們看一下第二步的操作,將名為adviceDef的RootBeanD轉(zhuǎn)換成名為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));
}

這里相當(dāng)于將上一步生成的RootBeanDefinition包裝了一下,new一個新的RootBeanDefinition出來,Class類型是org.springframework.aop.aspectj.AspectJPointcutAdvisor。

第4行~第7行的代碼是用于判斷標(biāo)簽中有沒有”order”屬性的,有就設(shè)置一下,”order”屬性是用來控制切入方法優(yōu)先級的。

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

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

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

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

第2行獲取注冊的名字BeanName,和<bean>的注冊差不多,使用的是Class全路徑+”#”+全局計數(shù)器的方式,其中的Class全路徑為org.springframework.aop.aspectj.AspectJPointcutAdvisor,依次類推,每一個BeanName應(yīng)當(dāng)為org.springframework.aop.aspectj.AspectJPointcutAdvisor#0、org.springframework.aop.aspectj.AspectJPointcutAdvisor#1、org.springframework.aop.aspectj.AspectJPointcutAdvisor#2這樣下去。
第3行向DefaultListableBeanFactory中注冊,BeanName已經(jīng)有了,剩下的就是Bean定義,Bean定義的解析流程之前已經(jīng)看過了,就不說了。

解析切面的過程

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

省略號部分表示是解析的是、這種標(biāo)簽,上部分已經(jīng)說過了,就不說了,下面看一下解析部分的源碼。

第5行~第7行的代碼構(gòu)建了一個Aspect標(biāo)簽組件定義,并將Apsect標(biāo)簽組件定義推到ParseContext即解析工具上下文中,這部分代碼不是關(guān)鍵。

第9行的代碼拿到所有下的pointcut標(biāo)簽,進(jìn)行遍歷,由parsePointcut方法進(jìn)行處理:

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行的代碼獲取標(biāo)簽下的”id”屬性與”expression”屬性。

第8行的代碼推送一個PointcutEntry,表示當(dāng)前Spring上下文正在解析Pointcut標(biāo)簽。

第9行的代碼創(chuàng)建Pointcut的Bean定義,之后再看,先把其他方法都看一下。

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

第12行~第18行的代碼用于注冊獲取到的Bean定義,默認(rèn)pointcutBeanName為標(biāo)簽中定義的id屬性:

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

第23行~第25行的代碼,finally塊在標(biāo)簽解析完畢后,讓之前推送至棧頂?shù)腜ointcutEntry出棧,表示此次標(biāo)簽解析完畢。

最后回頭來一下第9行代碼createPointcutDefinition的實現(xiàn),比較簡單:

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;
}

關(guān)鍵就是注意一下兩點:

標(biāo)簽對應(yīng)解析出來的BeanDefinition是RootBeanDefinition,且RootBenaDefinitoin中的Class是org.springframework.aop.aspectj.AspectJExpressionPointcut
標(biāo)簽對應(yīng)的Bean是prototype即原型的
這樣一個流程下來,就解析了標(biāo)簽中的內(nèi)容并將之轉(zhuǎn)換為RootBeanDefintion存儲在Spring容器中。

AOP為Bean生成代理的時機(jī)分析

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

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

AspectJAwareAdvisorAutoProxyCreator是BeanPostProcessor接口的實現(xiàn)類
postProcessBeforeInitialization方法與postProcessAfterInitialization方法實現(xiàn)在父類AbstractAutoProxyCreator中
postProcessBeforeInitialization方法是一個空實現(xiàn)
邏輯代碼在postProcessAfterInitialization方法中
基于以上的分析,將Bean生成代理的時機(jī)已經(jīng)一目了然了:在每個Bean初始化之后,如果需要,調(diào)用AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization為Bean生成代理。

代理對象實例化—-判斷是否為生成代理
上文分析了Bean生成代理的時機(jī)是在每個Bean初始化之后,下面把代碼定位到Bean初始化之后,先是AbstractAutowireCapableBeanFactory的initializeBean方法進(jìn)行初始化:

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;
}

這里調(diào)用每個BeanPostProcessor的postProcessBeforeInitialization方法。按照之前的分析,看一下AbstractAutoProxyCreator的postProcessAfterInitialization方法實現(xiàn):

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行是一些不需要生成代理的場景判斷,這里略過。首先我們要思考的第一個問題是:哪些目標(biāo)對象需要生成代理?因為配置文件里面有很多Bean,肯定不能對每個Bean都生成代理,因此需要一套規(guī)則判斷Bean是不是需要生成代理,這套規(guī)則就是第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,根據(jù)上文的配置文件,有兩個候選Advisor,分別是節(jié)點下的和這兩個,這兩個在XML解析的時候已經(jīng)被轉(zhuǎn)換生成了RootBeanDefinition。

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

第3行代碼,根據(jù)候選Advisors,尋找可以使用的Advisor,跟一下方法實現(xiàn):

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;
    }
}

第一個參數(shù)advisor的實際類型是AspectJPointcutAdvisor,它是PointcutAdvisor的子類,因此執(zhí)行第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;
}

這個方法其實就是拿當(dāng)前Advisor對應(yīng)的expression做了兩層判斷:

目標(biāo)類必須滿足expression的匹配規(guī)則
目標(biāo)類中的方法必須滿足expression的匹配規(guī)則,當(dāng)然這里方法不是全部需要滿足expression的匹配規(guī)則,有一個方法滿足即可
如果以上兩條都滿足,那么容器則會判斷該滿足條件,需要被生成代理對象,具體方式為返回一個數(shù)組對象,該數(shù)組對象中存儲的是對應(yīng)的Advisor。

代理對象實例化過程

代理對象實例化—-為生成代理代碼上下文梳理
上文分析了為生成代理的條件,現(xiàn)在就正式看一下Spring上下文是如何為生成代理的?;氐紸bstractAutoProxyCreator的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行拿到對應(yīng)的Advisor數(shù)組,第15行判斷只要Advisor數(shù)組不為空,那么就會通過第17行的代碼為創(chuàng)建代理:

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行的代碼做了一個判斷,判斷的內(nèi)容是這個節(jié)點中proxy-target-class=”false”或者proxy-target-class不配置,即不使用CGLIB生成代理。如果滿足條件,進(jìn)判斷,獲取當(dāng)前Bean實現(xiàn)的所有接口,講這些接口Class對象都添加到ProxyFactory中。

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

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

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

創(chuàng)建AopProxy接口實現(xiàn)類
通過AopProxy接口的實現(xiàn)類的getProxy方法獲取對應(yīng)的代理
就從這兩個點出發(fā),分兩部分分析一下。

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

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

前面的部分沒什么必要看,直接進(jìn)入重點即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方法。看到默認(rèn)是第19行的代碼使用JDK自帶的Proxy生成代理,碰到以下三種情況例外:

ProxyConfig的isOptimize方法為true,這表示讓Spring自己去優(yōu)化而不是用戶指定
ProxyConfig的isProxyTargetClass方法為true,這表示配置了proxy-target-class=”true”
ProxyConfig滿足hasNoUserSuppliedProxyInterfaces方法執(zhí)行結(jié)果為true,這表示對象沒有實現(xiàn)任何接口或者實現(xiàn)的接口是SpringProxy接口
在進(jìn)入第2行的if判斷之后再根據(jù)目標(biāo)的類型決定返回哪種AopProxy。簡單總結(jié)起來就是:

proxy-target-class沒有配置或者proxy-target-class=”false”,返回JdkDynamicAopProxy
proxy-target-class=”true”或者對象沒有實現(xiàn)任何接口或者只實現(xiàn)了SpringProxy接口,返回Cglib2AopProxy
當(dāng)然,不管是JdkDynamicAopProxy還是Cglib2AopProxy,AdvisedSupport都是作為構(gòu)造函數(shù)參數(shù)傳入的,里面存儲了具體的Advisor。

代理對象實例化—-通過getProxy方法獲取對應(yīng)的代理
其實代碼已經(jīng)分析到了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方法,同時都有的話打個標(biāo)記,尋找結(jié)束,equals方法和hashCode方法有特殊處理。

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

代理方法調(diào)用原理

前面已經(jīng)詳細(xì)分析了為接口/類生成代理的原理,生成代理之后就要調(diào)用方法了,這里看一下使用JdkDynamicAopProxy調(diào)用方法的原理。

由于JdkDynamicAopProxy本身實現(xiàn)了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方法即使?jié)M足expression規(guī)則,也不會為之產(chǎn)生代理內(nèi)容,調(diào)用的是JdkDynamicAopProxy的equals方法與hashCode方法。至于這兩個方法是什么作用,可以自己查看一下源代碼。

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

第27行~第30行的代碼,是用于判斷是否將代理暴露出去的,由標(biāo)簽中的expose-proxy=”true/false”配置。

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

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

第51行~第56行的代碼,如果攔截器列表不為空,按照注釋的意思,需要一個ReflectiveMethodInvocation,并通過proceed方法對原方法進(jìn)行攔截,proceed方法感興趣的朋友可以去看一下,里面使用到了遞歸的思想對chain中的Object進(jìn)行了層層的調(diào)用。

CGLIB代理實現(xiàn)

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

如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理

如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理

如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理

這里將攔截器鏈封裝到了DynamicAdvisedInterceptor中,并加入了Callback,DynamicAdvisedInterceptor實現(xiàn)了CGLIB的MethodInterceptor,所以其核心邏輯在intercept方法中:

如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理

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

看完上述內(nèi)容,你們對如何進(jìn)行Spring源碼剖析AOP實現(xiàn)原理有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI