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

前言java

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

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:spring

<?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:數據庫

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

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

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

正常來講,遇到 這兩個標籤的時候,都會執行第9行的代碼,由於 標籤是默認的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(
                                "<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循環只用來處理 標籤下的 這五個標籤的。

接着,若是是上述五種標籤之一,那麼進入第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,和 的註冊差很少,使用的是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處理 流程
回到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初始化以後,先是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的匹配規則,有一個方法知足便可
若是以上兩條都知足,那麼容器則會判斷該 知足條件,須要被生成代理對象,具體方式爲返回一個數組對象,該數組對象中存儲的是 對應的Advisor。

代理對象實例化過程

代理對象實例化—-爲 生成代理代碼上下文梳理
上文分析了爲 生成代理的條件,如今就正式看一下Spring上下文是如何爲 生成代理的。回到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行拿到 對應的Advisor數組,第15行判斷只要Advisor數組不爲空,那麼就會經過第17行的代碼爲 建立代理:

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方法獲取 對應的代理
就從這兩個點出發,分兩部分分析一下。

代理對象實例化—-建立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,這表示 對象沒有實現任何接口或者實現的接口是SpringProxy接口
在進入第2行的if判斷以後再根據目標 的類型決定返回哪一種AopProxy。簡單總結起來就是:

proxy-target-class沒有配置或者proxy-target-class=」false」,返回JdkDynamicAopProxy
proxy-target-class=」true」或者 對象沒有實現任何接口或者只實現了SpringProxy接口,返回Cglib2AopProxy
固然,不論是JdkDynamicAopProxy仍是Cglib2AopProxy,AdvisedSupport都是做爲構造函數參數傳入的,裏面存儲了具體的Advisor。

代理對象實例化—-經過getProxy方法獲取 對應的代理
其實代碼已經分析到了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以及其建立代理的方式:

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

這裏咱們看到了與JDK動態代理一樣的獲取攔截器鏈的過程,而且CglibMethodInvokcation繼承了咱們在JDK動態代理看到的ReflectiveMethodInvocation,可是並無重寫其proceed方法,只是重寫了執行目標方法的邏輯,因此總體上是大同小異的。

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

微信公衆號【黃小斜】做者是螞蟻金服 JAVA 工程師,專一於 JAVA 後端技術棧:SpringBoot、SSM全家桶、MySQL、分佈式、中間件、微服務,同時也懂點投資理財,堅持學習和寫做,相信終身學習的力量!關注公衆號後回覆」架構師「便可領取 Java基礎、進階、項目和架構師等免費學習資料,更有數據庫、分佈式、微服務等熱門技術學習視頻,內容豐富,兼顧原理和實踐,另外也將贈送做者原創的Java學習指南、Java程序員面試指南等乾貨資源

相關文章
相關標籤/搜索