欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring5 源码深度解析----- AOP代理的生成

程序员文章站 2022-06-29 13:48:48
在获取了所有对应bean的增强后,便可以进行代理的创建了。回到AbstractAutoProxyCreator的wrapIfNecessary方法中,如下所示: 我们上一篇文章分析完了第16行,获取到了所有对应bean的增强器,并获取到了此目标bean所有匹配的 Advisor,接下来我们要从第17 ......

在获取了所有对应bean的增强后,便可以进行代理的创建了。回到abstractautoproxycreator的wrapifnecessary方法中,如下所示: 

 1 protected static final object[] do_not_proxy = null;
 2 
 3 protected object wrapifnecessary(object bean, string beanname, object cachekey) {
 4     if (stringutils.haslength(beanname) && this.targetsourcedbeans.contains(beanname)) {
 5         return bean;
 6     }
 7     if (boolean.false.equals(this.advisedbeans.get(cachekey))) {
 8         return bean;
 9     }
10     if (isinfrastructureclass(bean.getclass()) || shouldskip(bean.getclass(), beanname)) {
11         this.advisedbeans.put(cachekey, boolean.false);
12         return bean;
13     }
14 
15     // create proxy if we have advice.
16     object[] specificinterceptors = getadvicesandadvisorsforbean(bean.getclass(), beanname, null);
17     if (specificinterceptors != do_not_proxy) {
18         this.advisedbeans.put(cachekey, boolean.true);
19         object proxy = createproxy(
20                 bean.getclass(), beanname, specificinterceptors, new singletontargetsource(bean));
21         this.proxytypes.put(cachekey, proxy.getclass());
22         return proxy;
23     }
24 
25     this.advisedbeans.put(cachekey, boolean.false);
26     return bean;
27 }

我们上一篇文章分析完了第16行,获取到了所有对应bean的增强器,并获取到了此目标bean所有匹配的 advisor,接下来我们要从第17行开始分析,如果 specificinterceptors 不为空,则要为当前bean创建代理类,接下来我们来看创建代理类的方法 createproxy:

protected object createproxy(class<?> beanclass, @nullable string beanname,
        @nullable object[] specificinterceptors, targetsource targetsource) {

    if (this.beanfactory instanceof configurablelistablebeanfactory) {
        autoproxyutils.exposetargetclass((configurablelistablebeanfactory) this.beanfactory, beanname, beanclass);
    }

    proxyfactory proxyfactory = new proxyfactory();
    // 获取当前类中相关属性
    proxyfactory.copyfrom(this);

    if (!proxyfactory.isproxytargetclass()) {
        // 决定对于给定的bean是否应该使用targetclass而不是他的接口代理,
        // 检査 proxytargetclass 设置以及 preservetargetclass 属性
        if (shouldproxytargetclass(beanclass, beanname)) {
            proxyfactory.setproxytargetclass(true);
        }
        else {
            evaluateproxyinterfaces(beanclass, proxyfactory);
        }
    }

    advisor[] advisors = buildadvisors(beanname, specificinterceptors);
    // 加入增强器
    proxyfactory.addadvisors(advisors);
    // 设置要代理的目标类
    proxyfactory.settargetsource(targetsource);
    // 定制代理
    customizeproxyfactory(proxyfactory);
    // 用来控制代理工厂被配置之后,是否还允许修改通知。
    // 缺省值是false (即在代理被配置之后,不允许修改代理的配置)。
    proxyfactory.setfrozen(this.freezeproxy);
    if (advisorsprefiltered()) {
        proxyfactory.setprefiltered(true);
    }

    //真正创建代理的方法
    return proxyfactory.getproxy(getproxyclassloader());
}

@override
public void settargetsource(@nullable targetsource targetsource) {
    this.targetsource = (targetsource != null ? targetsource : empty_target_source);
}

public void addadvisors(collection<advisor> advisors) {
    if (isfrozen()) {
        throw new aopconfigexception("cannot add advisor: configuration is frozen.");
    }
    if (!collectionutils.isempty(advisors)) {
        for (advisor advisor : advisors) {
            if (advisor instanceof introductionadvisor) {
                validateintroductionadvisor((introductionadvisor) advisor);
            }
            assert.notnull(advisor, "advisor must not be null");
            this.advisors.add(advisor);
        }
        updateadvisorarray();
        advicechanged();
    }
}

从上面代码我们看到对于代理类的创建及处理spring是委托给了proxyfactory处理的

创建代理

public object getproxy(@nullable classloader classloader) {
    return createaopproxy().getproxy(classloader);
}

在上面的getproxy方法中createaopproxy方法,其实现是在defaultaopproxyfactory中,这个方法的主要功能是,根据optimize、proxytargetclass等参数来决定生成jdk动态代理,还是生成cglib代理。我们进入到方法内:

protected final synchronized aopproxy createaopproxy() {
    if (!this.active) {
        activate();
    }
    // 创建代理
    return getaopproxyfactory().createaopproxy(this);
}

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.");
        }
        //手动设置创建cglib代理类后,如果目标bean是一个接口,也要创建jdk代理类
        if (targetclass.isinterface() || proxy.isproxyclass(targetclass)) {
            return new jdkdynamicaopproxy(config);
        }
        //创建cglib代理
        return new objenesiscglibaopproxy(config);
    }
    else {
        //默认创建jdk代理
        return new jdkdynamicaopproxy(config);
    }
}

我们知道对于spring的代理是通过jdkproxy的实现和cglibproxy实现。spring是如何选取的呢?

从if的判断条件中可以看到3个方面影响这spring的判断。

  • optimize:用来控制通过cglib创建的代理是否使用激进的优化策略,除非完全了解aop代理如何处理优化,否则不推荐用户使用这个设置。目前这个属性仅用于cglib 代理,对于jdk动态代理(缺省代理)无效。

  • proxytargetclass:这个属性为true时,目标类本身被代理而不是目标类的接口。如果这个属性值被设为true,cglib代理将被创建,设置方式:<aop:aspectj-autoproxy proxy-target-class="true"/>。

  • hasnousersuppliedproxylnterfaces:是否存在代理接口

下面是对jdk与cglib方式的总结。

  • 如果目标对象实现了接口,默认情况下会采用jdk的动态代理实现aop。

  • 如果目标对象实现了接口,可以强制使用cglib实现aop。

  • 如果目标对象没有实现了接口,必须采用cglib库,spring会自动在jdk动态代理 和cglib之间转换。

如何强制使用cglib实现aop?

(1)添加 cglib 库,spring_home/cglib/*.jar。

(2)在 spring 配置文件中加人<aop:aspectj-autoproxy proxy-target-class="true"/>。

jdk动态代理和cglib字节码生成的区别?

  • jdk动态代理只能对实现了接口的类生成代理,而不能针对类。
  • cglib是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法,因为是继承,所以该类或方法最好不要声明成final。

获取代理

本文主要介绍jdk动态代理类的实现,在此之前,有必要熟悉一下jdk代理使用示例,请看我以前的博文,jdk动态代理源码分析文章《》

spring的aop实现其实也是用了proxy和invocationhandler这两个东西的。

我们再次来回顾一下使用jdk代理的方式,在整个创建过程中,对于invocationhandler的创建是最为核心的,在自定义的invocationhandler中需要重写3个函数。

  • 构造函数,将代理的对象传入。
  • invoke方法,此方法中实现了 aop增强的所有逻辑。
  • getproxy方法,此方法千篇一律,但是必不可少。

那么,我们看看spring中的jdk代理实现是不是也是这么做的呢?我们来看看简化后的 jdkdynamicaopproxy  。

  1 final class jdkdynamicaopproxy implements aopproxy, invocationhandler, serializable {
  2 
  3     private final advisedsupport advised;
  4 
  5     public jdkdynamicaopproxy(advisedsupport config) throws aopconfigexception {
  6         assert.notnull(config, "advisedsupport must not be null");
  7         if (config.getadvisors().length == 0 && config.gettargetsource() == advisedsupport.empty_target_source) {
  8             throw new aopconfigexception("no advisors and no targetsource specified");
  9         }
 10         this.advised = config;
 11     }
 12 
 13 
 14     @override
 15     public object getproxy() {
 16         return getproxy(classutils.getdefaultclassloader());
 17     }
 18 
 19     @override
 20     public object getproxy(@nullable classloader classloader) {
 21         if (logger.istraceenabled()) {
 22             logger.trace("creating jdk dynamic proxy: " + this.advised.gettargetsource());
 23         }
 24         class<?>[] proxiedinterfaces = aopproxyutils.completeproxiedinterfaces(this.advised, true);
 25         finddefinedequalsandhashcodemethods(proxiedinterfaces);
 26         return proxy.newproxyinstance(classloader, proxiedinterfaces, this);
 27     }
 28 
 29     @override
 30     @nullable
 31     public object invoke(object proxy, method method, object[] args) throws throwable {
 32         object oldproxy = null;
 33         boolean setproxycontext = false;
 34 
 35         targetsource targetsource = this.advised.targetsource;
 36         object target = null;
 37 
 38         try {
 39             if (!this.equalsdefined && aoputils.isequalsmethod(method)) {
 40                 // the target does not implement the equals(object) method itself.
 41                 return equals(args[0]);
 42             }
 43             else if (!this.hashcodedefined && aoputils.ishashcodemethod(method)) {
 44                 // the target does not implement the hashcode() method itself.
 45                 return hashcode();
 46             }
 47             else if (method.getdeclaringclass() == decoratingproxy.class) {
 48                 // there is only getdecoratedclass() declared -> dispatch to proxy config.
 49                 return aopproxyutils.ultimatetargetclass(this.advised);
 50             }
 51             else if (!this.advised.opaque && method.getdeclaringclass().isinterface() &&
 52                     method.getdeclaringclass().isassignablefrom(advised.class)) {
 53                 // service invocations on proxyconfig with the proxy config...
 54                 return aoputils.invokejoinpointusingreflection(this.advised, method, args);
 55             }
 56 
 57             object retval;
 58 
 59             if (this.advised.exposeproxy) {
 60                 // make invocation available if necessary.
 61                 oldproxy = aopcontext.setcurrentproxy(proxy);
 62                 setproxycontext = true;
 63             }
 64 
 65             // get as late as possible to minimize the time we "own" the target,
 66             // in case it comes from a pool.
 67             target = targetsource.gettarget();
 68             class<?> targetclass = (target != null ? target.getclass() : null);
 69 
 70             // get the interception chain for this method.
 71             list<object> chain = this.advised.getinterceptorsanddynamicinterceptionadvice(method, targetclass);
 72 
 73             // check whether we have any advice. if we don't, we can fallback on direct
 74             // reflective invocation of the target, and avoid creating a methodinvocation.
 75             if (chain.isempty()) {
 76                 // we can skip creating a methodinvocation: just invoke the target directly
 77                 // note that the final invoker must be an invokerinterceptor so we know it does
 78                 // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
 79                 object[] argstouse = aopproxyutils.adaptargumentsifnecessary(method, args);
 80                 retval = aoputils.invokejoinpointusingreflection(target, method, argstouse);
 81             }
 82             else {
 83                 // we need to create a method invocation...
 84                 methodinvocation invocation =
 85                         new reflectivemethodinvocation(proxy, target, method, args, targetclass, chain);
 86                 // proceed to the joinpoint through the interceptor chain.
 87                 retval = invocation.proceed();
 88             }
 89 
 90             // massage return value if necessary.
 91             class<?> returntype = method.getreturntype();
 92             if (retval != null && retval == target &&
 93                     returntype != object.class && returntype.isinstance(proxy) &&
 94                     !rawtargetaccess.class.isassignablefrom(method.getdeclaringclass())) {
 95                 // special case: it returned "this" and the return type of the method
 96                 // is type-compatible. note that we can't help if the target sets
 97                 // a reference to itself in another returned object.
 98                 retval = proxy;
 99             }
100             else if (retval == null && returntype != void.type && returntype.isprimitive()) {
101                 throw new aopinvocationexception(
102                         "null return value from advice does not match primitive return type for: " + method);
103             }
104             return retval;
105         }
106         finally {
107             if (target != null && !targetsource.isstatic()) {
108                 // must have come from targetsource.
109                 targetsource.releasetarget(target);
110             }
111             if (setproxycontext) {
112                 // restore old proxy.
113                 aopcontext.setcurrentproxy(oldproxy);
114             }
115         }
116     }
117 
118 }

我们看到jdkdynamicaopproxy 也是和我们自定义的invocationhandler一样,实现了invocationhandler接口,并且提供了一个getproxy方法创建代理类,重写invoke方法。

我们重点看看代理类的调用。了解jdk动态代理的话都会知道,在实现jdk动态代理功能,要实现invocationhandler接口的invoke方法(这个方法是一个回调方法)。 被代理类中的方法被调用时,实际上是调用的invoke方法,我们看一看这个方法的实现。

 1 @override
 2 @nullable
 3 public object invoke(object proxy, method method, object[] args) throws throwable {
 4     methodinvocation invocation;
 5     object oldproxy = null;
 6     boolean setproxycontext = false;
 7 
 8     targetsource targetsource = this.advised.targetsource;
 9     object target = null;
10 
11     try {
12         if (!this.equalsdefined && aoputils.isequalsmethod(method)) {
13             return equals(args[0]);
14         }
15         else if (!this.hashcodedefined && aoputils.ishashcodemethod(method)) {
16             return hashcode();
17         }
18         else if (method.getdeclaringclass() == decoratingproxy.class) {
19             return aopproxyutils.ultimatetargetclass(this.advised);
20         }
21         else if (!this.advised.opaque && method.getdeclaringclass().isinterface() &&
22                 method.getdeclaringclass().isassignablefrom(advised.class)) {
23             return aoputils.invokejoinpointusingreflection(this.advised, method, args);
24         }
25 
26         object retval;
27         if (this.advised.exposeproxy) {
28             // make invocation available if necessary.
29             oldproxy = aopcontext.setcurrentproxy(proxy);
30             setproxycontext = true;
31         }
32 
33         target = targetsource.gettarget();
34         class<?> targetclass = (target != null ? target.getclass() : null);
35 
36         // 获取当前方法的拦截器链
37         list<object> chain = this.advised.getinterceptorsanddynamicinterceptionadvice(method, targetclass);
38 
39         if (chain.isempty()) {
40             // 如果没有发现任何拦截器那么直接调用切点方法
41             object[] argstouse = aopproxyutils.adaptargumentsifnecessary(method, args);
42             retval = aoputils.invokejoinpointusingreflection(target, method, argstouse);
43         }
44         else {
45             // we need to create a method invocation...
46             // 将拦截器封装在reflectivemethodinvocation,
47             // 以便于使用其proceed进行链接表用拦截器
48             invocation = new reflectivemethodinvocation(proxy, target, method, args, targetclass, chain);
49             // proceed to the joinpoint through the interceptor chain.
50             // 执行拦截器链
51             retval = invocation.proceed();
52         }
53 
54         class<?> returntype = method.getreturntype();
55         // 返回结果
56         if (retval != null && retval == target &&
57                 returntype != object.class && returntype.isinstance(proxy) &&
58                 !rawtargetaccess.class.isassignablefrom(method.getdeclaringclass())) {
59             retval = proxy;
60         }
61         else if (retval == null && returntype != void.type && returntype.isprimitive()) {
62             throw new aopinvocationexception(
63                     "null return value from advice does not match primitive return type for: " + method);
64         }
65         return retval;
66     }
67     finally {
68         if (target != null && !targetsource.isstatic()) {
69             // must have come from targetsource.
70             targetsource.releasetarget(target);
71         }
72         if (setproxycontext) {
73             // restore old proxy.
74             aopcontext.setcurrentproxy(oldproxy);
75         }
76     }
77 }

 

我们先来看看第37行,获取目标bean中目标method中的增强器,并将增强器封装成拦截器链

 1 @override
 2 public list<object> getinterceptorsanddynamicinterceptionadvice(
 3         advised config, method method, @nullable class<?> targetclass) {
 4 
 5     // this is somewhat tricky... we have to process introductions first,
 6     // but we need to preserve order in the ultimate list.
 7     advisoradapterregistry registry = globaladvisoradapterregistry.getinstance();
 8     advisor[] advisors = config.getadvisors();
 9     list<object> interceptorlist = new arraylist<>(advisors.length);
10     class<?> actualclass = (targetclass != null ? targetclass : method.getdeclaringclass());
11     boolean hasintroductions = null;
12 
13     //获取bean中的所有增强器
14     for (advisor advisor : advisors) {
15         if (advisor instanceof pointcutadvisor) {
16             // add it conditionally.
17             pointcutadvisor pointcutadvisor = (pointcutadvisor) advisor;
18             if (config.isprefiltered() || pointcutadvisor.getpointcut().getclassfilter().matches(actualclass)) {
19                 methodmatcher mm = pointcutadvisor.getpointcut().getmethodmatcher();
20                 boolean match;
21                 if (mm instanceof introductionawaremethodmatcher) {
22                     if (hasintroductions == null) {
23                         hasintroductions = hasmatchingintroductions(advisors, actualclass);
24                     }
25                     match = ((introductionawaremethodmatcher) mm).matches(method, actualclass, hasintroductions);
26                 }
27                 else {
28                     //根据增强器中的pointcut判断增强器是否能匹配当前类中的method
29                     //我们要知道目标bean中并不是所有的方法都需要增强,也有一些普通方法
30                     match = mm.matches(method, actualclass);
31                 }
32                 if (match) {
33                     //如果能匹配,就将advisor封装成methodinterceptor加入到interceptorlist中
34                     methodinterceptor[] interceptors = registry.getinterceptors(advisor);
35                     if (mm.isruntime()) {
36                         // creating a new object instance in the getinterceptors() method
37                         // isn't a problem as we normally cache created chains.
38                         for (methodinterceptor interceptor : interceptors) {
39                             interceptorlist.add(new interceptoranddynamicmethodmatcher(interceptor, mm));
40                         }
41                     }
42                     else {
43                         interceptorlist.addall(arrays.aslist(interceptors));
44                     }
45                 }
46             }
47         }
48         else if (advisor instanceof introductionadvisor) {
49             introductionadvisor ia = (introductionadvisor) advisor;
50             if (config.isprefiltered() || ia.getclassfilter().matches(actualclass)) {
51                 interceptor[] interceptors = registry.getinterceptors(advisor);
52                 interceptorlist.addall(arrays.aslist(interceptors));
53             }
54         }
55         else {
56             interceptor[] interceptors = registry.getinterceptors(advisor);
57             interceptorlist.addall(arrays.aslist(interceptors));
58         }
59     }
60 
61     return interceptorlist;
62 }

 

我们知道目标bean中并不是所有的方法都需要增强,所以我们要遍历所有的 advisor ,根据pointcut判断增强器是否能匹配当前类中的method,取出能匹配的增强器,封装成 methodinterceptor,加入到拦截器链中,我们来看看第34行

@override
public methodinterceptor[] getinterceptors(advisor advisor) throws unknownadvicetypeexception {
    list<methodinterceptor> interceptors = new arraylist<>(3);
    advice advice = advisor.getadvice();
    if (advice instanceof methodinterceptor) {
        interceptors.add((methodinterceptor) advice);
    }
    //这里遍历三个适配器,将对应的advisor转化成interceptor
    //这三个适配器分别是methodbeforeadviceadapter,afterreturningadviceadapter,throwsadviceadapter
    for (advisoradapter adapter : this.adapters) {
        if (adapter.supportsadvice(advice)) {
            interceptors.add(adapter.getinterceptor(advisor));
        }
    }
    if (interceptors.isempty()) {
        throw new unknownadvicetypeexception(advisor.getadvice());
    }
    return interceptors.toarray(new methodinterceptor[0]);
}

private final list<advisoradapter> adapters = new arraylist<>(3);

/**
 * create a new defaultadvisoradapterregistry, registering well-known adapters.
 */
public defaultadvisoradapterregistry() {
    registeradvisoradapter(new methodbeforeadviceadapter());
    registeradvisoradapter(new afterreturningadviceadapter());
    registeradvisoradapter(new throwsadviceadapter());
}

@override
public void registeradvisoradapter(advisoradapter adapter) {
    this.adapters.add(adapter);
}

由于spring中涉及过多的拦截器,增强器,增强方法等方式来对逻辑进行增强,在上一篇文章中我们知道创建的几个增强器,aspectjaroundadvice、aspectjafteradvice、aspectjafterthrowingadvice这几个增强器都实现了 methodinterceptor 接口,aspectjmethodbeforeadvice 和aspectjafterreturningadvice 并没有实现 methodinterceptor 接口,因此aspectjmethodbeforeadvice 和aspectjafterreturningadvice不能满足methodinterceptor 接口中的invoke方法,所以这里使用适配器模式将aspectjmethodbeforeadvice 和aspectjafterreturningadvice转化成能满足需求的methodinterceptor实现类。

遍历adapters,通过adapter.supportsadvice(advice)找到advice对应的适配器,adapter.getinterceptor(advisor)将advisor转化成对应的interceptor

我们来看看这几个增强器

aspectjaroundadvice

public class aspectjaroundadvice extends abstractaspectjadvice implements methodinterceptor, serializable {

    public aspectjaroundadvice(
            method aspectjaroundadvicemethod, aspectjexpressionpointcut pointcut, aspectinstancefactory aif) {

        super(aspectjaroundadvicemethod, pointcut, aif);
    }

    @override
    public boolean isbeforeadvice() {
        return false;
    }

    @override
    public boolean isafteradvice() {
        return false;
    }

    @override
    public object invoke(methodinvocation mi) throws throwable {
        if (!(mi instanceof proxymethodinvocation)) {
            throw new illegalstateexception("methodinvocation is not a spring proxymethodinvocation: " + mi);
        }
        proxymethodinvocation pmi = (proxymethodinvocation) mi;
        proceedingjoinpoint pjp = lazygetproceedingjoinpoint(pmi);
        joinpointmatch jpm = getjoinpointmatch(pmi);
        return invokeadvicemethod(pjp, jpm, null, null);
    }

}

aspectjmethodbeforeadvice

public class aspectjmethodbeforeadvice extends abstractaspectjadvice implements methodbeforeadvice, serializable {

    public aspectjmethodbeforeadvice(
            method aspectjbeforeadvicemethod, aspectjexpressionpointcut pointcut, aspectinstancefactory aif) {

        super(aspectjbeforeadvicemethod, pointcut, aif);
    }

    @override
    public void before(method method, object[] args, @nullable object target) throws throwable {
        invokeadvicemethod(getjoinpointmatch(), null, null);
    }

    @override
    public boolean isbeforeadvice() {
        return true;
    }

    @override
    public boolean isafteradvice() {
        return false;
    }

}

aspectjafteradvice

public class aspectjafteradvice extends abstractaspectjadvice
        implements methodinterceptor, afteradvice, serializable {

    public aspectjafteradvice(
            method aspectjbeforeadvicemethod, aspectjexpressionpointcut pointcut, aspectinstancefactory aif) {

        super(aspectjbeforeadvicemethod, pointcut, aif);
    }


    @override
    public object invoke(methodinvocation mi) throws throwable {
        try {
            return mi.proceed();
        }
        finally {
            invokeadvicemethod(getjoinpointmatch(), null, null);
        }
    }

    @override
    public boolean isbeforeadvice() {
        return false;
    }

    @override
    public boolean isafteradvice() {
        return true;
    }

}

aspectjafterreturningadvice

public class aspectjafterreturningadvice extends abstractaspectjadvice
        implements afterreturningadvice, afteradvice, serializable {

    public aspectjafterreturningadvice(
            method aspectjbeforeadvicemethod, aspectjexpressionpointcut pointcut, aspectinstancefactory aif) {

        super(aspectjbeforeadvicemethod, pointcut, aif);
    }


    @override
    public boolean isbeforeadvice() {
        return false;
    }

    @override
    public boolean isafteradvice() {
        return true;
    }

    @override
    public void afterreturning(@nullable object returnvalue, method method, object[] args, @nullable object target) throws throwable {
        if (shouldinvokeonreturnvalueof(method, returnvalue)) {
            invokeadvicemethod(getjoinpointmatch(), returnvalue, null);
        }
    }
}

aspectjafterthrowingadvice

public class aspectjafterthrowingadvice extends abstractaspectjadvice
        implements methodinterceptor, afteradvice, serializable {

    public aspectjafterthrowingadvice(
            method aspectjbeforeadvicemethod, aspectjexpressionpointcut pointcut, aspectinstancefactory aif) {

        super(aspectjbeforeadvicemethod, pointcut, aif);
    }


    @override
    public boolean isbeforeadvice() {
        return false;
    }

    @override
    public boolean isafteradvice() {
        return true;
    }

    @override
    public object invoke(methodinvocation mi) throws throwable {
        try {
            return mi.proceed();
        }
        catch (throwable ex) {
            if (shouldinvokeonthrowing(ex)) {
                invokeadvicemethod(getjoinpointmatch(), null, ex);
            }
            throw ex;
        }
    }

}

接下来我们看看methodbeforeadviceadapter和afterreturningadviceadapter这两个适配器,这两个适配器是将methodbeforeadvice和afterreturningadvice适配成对应的interceptor

methodbeforeadviceadapter

class methodbeforeadviceadapter implements advisoradapter, serializable {
    @override
    public boolean supportsadvice(advice advice) {
        //判断是否是methodbeforeadvice类型的advice
        return (advice instanceof methodbeforeadvice);
    }

    @override
    public methodinterceptor getinterceptor(advisor advisor) {
        methodbeforeadvice advice = (methodbeforeadvice) advisor.getadvice();
        //将advice封装成methodbeforeadviceinterceptor
        return new methodbeforeadviceinterceptor(advice);
    }
}

//methodbeforeadviceinterceptor实现了methodinterceptor接口,实现了invoke方法,并将advice作为属性
public class methodbeforeadviceinterceptor implements methodinterceptor, beforeadvice, serializable {

    private final methodbeforeadvice advice;

    public methodbeforeadviceinterceptor(methodbeforeadvice advice) {
        assert.notnull(advice, "advice must not be null");
        this.advice = advice;
    }
    
    @override
    public object invoke(methodinvocation mi) throws throwable {
        this.advice.before(mi.getmethod(), mi.getarguments(), mi.getthis());
        return mi.proceed();
    }

}

afterreturningadviceadapter

class afterreturningadviceadapter implements advisoradapter, serializable {
    @override
    public boolean supportsadvice(advice advice) {
        return (advice instanceof afterreturningadvice);
    }

    @override
    public methodinterceptor getinterceptor(advisor advisor) {
        afterreturningadvice advice = (afterreturningadvice) advisor.getadvice();
        return new afterreturningadviceinterceptor(advice);
    }
}

public class afterreturningadviceinterceptor implements methodinterceptor, afteradvice, serializable {

    private final afterreturningadvice advice;

    public afterreturningadviceinterceptor(afterreturningadvice advice) {
        assert.notnull(advice, "advice must not be null");
        this.advice = advice;
    }

    @override
    public object invoke(methodinvocation mi) throws throwable {
        object retval = mi.proceed();
        this.advice.afterreturning(retval, mi.getmethod(), mi.getarguments(), mi.getthis());
        return retval;
    }

}

至此我们获取到了一个拦截器链,链中包括aspectjaroundadvice、aspectjafteradvice、aspectjafterthrowingadvice、methodbeforeadviceinterceptor、afterreturningadviceinterceptor

接下来 reflectivemethodinvocation 类进行了链的封装,而在reflectivemethodinvocation类的proceed方法中实现了拦截器的逐一调用,那么我们继续来探究,在proceed方法中是怎么实现前置增强在目标方法前调用后置增强在目标方法后调用的逻辑呢?

我们先来看看reflectivemethodinvocation的构造器,只是简单的进行属性赋值,不过我们要注意有一个特殊的变量currentinterceptorindex,这个变量代表执行interceptor的下标,从-1开始,interceptor执行一个,先++this.currentinterceptorindex

protected reflectivemethodinvocation(
        object proxy, @nullable object target, method method, @nullable object[] arguments,
        @nullable class<?> targetclass, list<object> interceptorsanddynamicmethodmatchers) {

    this.proxy = proxy;
    this.target = target;
    this.targetclass = targetclass;
    this.method = bridgemethodresolver.findbridgedmethod(method);
    this.arguments = aopproxyutils.adaptargumentsifnecessary(method, arguments);
    this.interceptorsanddynamicmethodmatchers = interceptorsanddynamicmethodmatchers;
}

private int currentinterceptorindex = -1;

下面是reflectivemethodinvocation类proceed方法:

public object proceed() throws throwable {
    // 首先,判断是不是所有的interceptor(也可以想像成advisor)都被执行完了。
    // 判断的方法是看currentinterceptorindex这个变量的值,增加到interceptor总个数这个数值没有,
    // 如果到了,就执行被代理方法(invokejoinpoint());如果没到,就继续执行interceptor。
    if (this.currentinterceptorindex == this.interceptorsanddynamicmethodmatchers.size() - 1) {
        return invokejoinpoint();
    }

    // 如果interceptor没有被全部执行完,就取出要执行的interceptor,并执行。
    // currentinterceptorindex先自增
    object interceptororinterceptionadvice =this.interceptorsanddynamicmethodmatchers.get(++this.currentinterceptorindex);
    // 如果interceptor是pointcut类型
    if (interceptororinterceptionadvice instanceof interceptoranddynamicmethodmatcher) {
        interceptoranddynamicmethodmatcher dm = (interceptoranddynamicmethodmatcher) interceptororinterceptionadvice;
        // 如果当前方法符合interceptor的pointcut限制,就执行interceptor
        if (dm.methodmatcher.matches(this.method, this.targetclass, this.arguments)) {
           // 这里将this当变量传进去,这是非常重要的一点
            return dm.interceptor.invoke(this);
        }
        // 如果不符合,就跳过当前interceptor,执行下一个interceptor
        else {
            return proceed();
        }
    }
    // 如果interceptor不是pointcut类型,就直接执行interceptor里面的增强。
    else {
        return ((methodinterceptor) interceptororinterceptionadvice).invoke(this);
    }
}

由于篇幅过程,目标方法和增强方法是如何执行的,我们将重新写一篇文章来讲解