30個(gè)類手寫Spring核心原理之AOP代碼織入(5)

本文節(jié)選自《Spring 5核心原理》

前面我們已經(jīng)完成了Spring IoC、DI、MVC三大核心模塊的功能,并保證了功能可用。接下來要完成Spring的另一個(gè)核心模塊—AOP,這也是最難的部分。

1 基礎(chǔ)配置

首先,在application.properties中增加如下自定義配置,作為Spring AOP的基礎(chǔ)配置:


#多切面配置可以在key前面加前綴
#例如 aspect.logAspect.

#切面表達(dá)式#
pointCut=public .* com.tom.spring.demo.service..*Service..*(.*)
#切面類#
aspectClass=com.tom.spring.demo.aspect.LogAspect
#切面前置通知#
aspectBefore=before
#切面后置通知#
aspectAfter=after
#切面異常通知#
aspectAfterThrow=afterThrowing
#切面異常類型#
aspectAfterThrowingName=java.lang.Exception

為了加強(qiáng)理解,我們對(duì)比一下Spring AOP的原生配置:


<bean id="xmlAspect" class="com.gupaoedu.aop.aspect.XmlAspect"></bean>

<!-- AOP配置 -->
<aop:config>

   <!-- 聲明一個(gè)切面,并注入切面Bean,相當(dāng)于@Aspect -->
   <aop:aspect ref="xmlAspect">
      <!-- 配置一個(gè)切入點(diǎn),相當(dāng)于@Pointcut -->
      <aop:pointcut expression="execution(* com.gupaoedu.aop.service..*(..))" id="simplePointcut"/>
      <!-- 配置通知,相當(dāng)于@Before、@After、@AfterReturn、@Around、@AfterThrowing -->
      <aop:before pointcut-ref="simplePointcut" method="before"/>
      <aop:after pointcut-ref="simplePointcut" method="after"/>
      <aop:after-returning pointcut-ref="simplePointcut" method="afterReturn"/>
      <aop:after-throwing pointcut-ref="simplePointcut" method="afterThrow" throwing="ex"/>
   </aop:aspect>

</aop:config>

為了方便,我們用properties文件來代替XML,以簡化操作。

2 AOP核心原理V1.0版本

AOP的基本實(shí)現(xiàn)原理是利用動(dòng)態(tài)代理機(jī)制,創(chuàng)建一個(gè)新的代理類完成代碼織入,以達(dá)到代碼功能增強(qiáng)的目的。如果各位小伙伴對(duì)動(dòng)態(tài)代理原理不太了解的話,可以回看一下我前段時(shí)間更新的“設(shè)計(jì)模式就該這樣學(xué)”系列中的動(dòng)態(tài)代理模式專題文章。那么Spring AOP又是如何利用動(dòng)態(tài)代理工作的呢?其實(shí)Spring主要功能就是完成解耦,將我們需要增強(qiáng)的代碼邏輯單獨(dú)拆離出來放到專門的類中,然后,通過聲明配置文件來關(guān)聯(lián)這些已經(jīng)被拆離的邏輯,最后合并到一起運(yùn)行。Spring容器為了保存這種關(guān)系,我們可以簡單的理解成Spring是用一個(gè)Map保存保存這種關(guān)聯(lián)關(guān)系的。Map的key就是我們要調(diào)用的目標(biāo)方法,Map的value就是我們要織入的方法。只不過要織入的方法有前后順序,因此我們需要標(biāo)記織入方法的位置。在目標(biāo)方法前面織入的邏輯叫做前置通知,在目標(biāo)方法后面織入的邏輯叫后置通知,在目標(biāo)方法出現(xiàn)異常時(shí)需要織入的邏輯叫異常通知。Map的具體設(shè)計(jì)如下:


private Map<Method,Map<String, Method>> methodAdvices = new HashMap<Method, Map<String, Method>>();

下面我完整的寫出一個(gè)簡易的ApplicationContex,小伙伴可以參考 一下:


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class GPApplicationContext {
    private Properties contextConfig = new Properties();
    private Map<String,Object> ioc = new HashMap<String,Object>();
    //用來保存配置文件中對(duì)應(yīng)的Method和Advice的對(duì)應(yīng)關(guān)系
    private Map<Method,Map<String, Method>> methodAdvices = new HashMap<Method, Map<String, Method>>();


    public GPApplicationContext(){
        
           //為了演示,手動(dòng)初始化一個(gè)Bean
             
        ioc.put("memberService", new MemberService());

        doLoadConfig("application.properties");

        doInitAopConfig();

    }

    public Object getBean(String name){
        return createProxy(ioc.get(name));
    }


    private Object createProxy(Object instance){
        return new GPJdkDynamicAopProxy(instance).getProxy();
    }

    //加載配置文件
    private void doLoadConfig(String contextConfigLocation) {
        //直接從類路徑下找到Spring主配置文件所在的路徑
        //并且將其讀取出來放到Properties對(duì)象中
        //相對(duì)于scanPackage=com.gupaoedu.demo 從文件中保存到了內(nèi)存中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doInitAopConfig() {

        try {
            Class apectClass = Class.forName(contextConfig.getProperty("aspectClass"));
            Map<String,Method> aspectMethods = new HashMap<String,Method>();
            for (Method method : apectClass.getMethods()) {
                aspectMethods.put(method.getName(),method);
            }

            //PonintCut  表達(dá)式解析為正則表達(dá)式
            String pointCut = contextConfig.getProperty("pointCut")
                    .replaceAll("\\.","\\\\.")
                    .replaceAll("\\\\.\\*",".*")
                    .replaceAll("\\(","\\\\(")
                    .replaceAll("\\)","\\\\)");
            Pattern pointCutPattern = Pattern.compile(pointCut);

            for (Map.Entry<String,Object> entry : ioc.entrySet()) {
                Class<?> clazz = entry.getValue().getClass();
                //循環(huán)找到所有的方法
                for (Method method : clazz.getMethods()) {
                    //保存方法名
                    String methodString = method.toString();
                    if(methodString.contains("throws")){
                        methodString = methodString.substring(0,methodString.lastIndexOf("throws")).trim();
                    }
                    Matcher matcher = pointCutPattern.matcher(methodString);
                    if(matcher.matches()){
                        Map<String,Method> advices = new HashMap<String,Method>();
                        if(!(null == contextConfig.getProperty("aspectBefore") || "".equals( contextConfig.getProperty("aspectBefore")))){
                            advices.put("before",aspectMethods.get(contextConfig.getProperty("aspectBefore")));
                        }
                        if(!(null ==  contextConfig.getProperty("aspectAfter") || "".equals( contextConfig.getProperty("aspectAfter")))){
                            advices.put("after",aspectMethods.get(contextConfig.getProperty("aspectAfter")));
                        }
                        if(!(null == contextConfig.getProperty("aspectAfterThrow") || "".equals( contextConfig.getProperty("aspectAfterThrow")))){
                            advices.put("afterThrow",aspectMethods.get(contextConfig.getProperty("aspectAfterThrow")));
                        }
                        methodAdvices.put(method,advices);
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    class GPJdkDynamicAopProxy implements GPInvocationHandler {
        private Object instance;
        public GPJdkDynamicAopProxy(Object instance) {
            this.instance = instance;
        }

        public Object getProxy() {
            return Proxy.newProxyInstance(instance.getClass().getClassLoader(),instance.getClass().getInterfaces(),this);
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object aspectObject = Class.forName(contextConfig.getProperty("aspectClass")).newInstance();
            Map<String,Method> advices = methodAdvices.get(instance.getClass().getMethod(method.getName(),method.getParameterTypes()));
            Object returnValue = null;
            advices.get("before").invoke(aspectObject);
            try {
                returnValue = method.invoke(instance, args);
            }catch (Exception e){
                advices.get("afterThrow").invoke(aspectObject);
                e.printStackTrace();
                throw e;
            }
            advices.get("after").invoke(aspectObject);
            return returnValue;
        }
    }

}

測試代碼:


public class MemberServiceTest {


    public static void main(String[] args) {
        GPApplicationContext applicationContext = new GPApplicationContext();
        IMemberService memberService = (IMemberService)applicationContext.getBean("memberService");

        try {

            memberService.get("1");
            memberService.save(new Member());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

我們通過簡單幾百行代碼,就可以完整地演示Spring AOP的核心原理,是不是很簡單呢?當(dāng)然,小伙伴們還是要自己動(dòng)手哈親自體驗(yàn)一下,這樣才會(huì)印象深刻。下面,我們繼續(xù)完善,將Spring AOP 1.0升級(jí)到2.0,那么2.0版本我是完全仿真Spring的原始設(shè)計(jì)來寫的,希望能夠給大家?guī)聿灰粯拥氖謱戵w驗(yàn),從而更加深刻地理解Spring AOP的原理。

3 完成AOP頂層設(shè)計(jì)

3.1 GPJoinPoint

定義一個(gè)切點(diǎn)的抽象,這是AOP的基礎(chǔ)組成單元。我們可以理解為這是某一個(gè)業(yè)務(wù)方法的附加信息。可想而知,切點(diǎn)應(yīng)該包含業(yè)務(wù)方法本身、實(shí)參列表和方法所屬的實(shí)例對(duì)象,還可以在GPJoinPoint中添加自定義屬性,看下面的代碼:


package com.tom.spring.formework.aop.aspect;

import java.lang.reflect.Method;

/**
 * 回調(diào)連接點(diǎn),通過它可以獲得被代理的業(yè)務(wù)方法的所有信息
 */
public interface GPJoinPoint {

    Method getMethod(); //業(yè)務(wù)方法本身

    Object[] getArguments();  //該方法的實(shí)參列表

    Object getThis(); //該方法所屬的實(shí)例對(duì)象

    //在JoinPoint中添加自定義屬性
    void setUserAttribute(String key, Object value);
    //從已添加的自定義屬性中獲取一個(gè)屬性值
    Object getUserAttribute(String key);

}

3.2 GPMethodInterceptor

方法攔截器是AOP代碼增強(qiáng)的基本組成單元,其子類主要有GPMethodBeforeAdvice、GPAfterReturningAdvice和GPAfterThrowingAdvice。


package com.tom.spring.formework.aop.intercept;

/**
 * 方法攔截器頂層接口
 */ 
public interface GPMethodInterceptor{
    Object invoke(GPMethodInvocation mi) throws Throwable;
}

3.3 GPAopConfig

定義AOP的配置信息的封裝對(duì)象,以方便在之后的代碼中相互傳遞。


package com.tom.spring.formework.aop;

import lombok.Data;

/**
 * AOP配置封裝
 */
@Data
public class GPAopConfig {
//以下配置與properties文件中的屬性一一對(duì)應(yīng)
    private String pointCut;  //切面表達(dá)式
    private String aspectBefore;  //前置通知方法名
    private String aspectAfter;  //后置通知方法名
    private String aspectClass;  //要織入的切面類
    private String aspectAfterThrow;  //異常通知方法名
    private String aspectAfterThrowingName;  //需要通知的異常類型
}

3.4 GPAdvisedSupport

GPAdvisedSupport主要完成對(duì)AOP配置的解析。其中pointCutMatch()方法用來判斷目標(biāo)類是否符合切面規(guī)則,從而決定是否需要生成代理類,對(duì)目標(biāo)方法進(jìn)行增強(qiáng)。而getInterceptorsAndDynamic- InterceptionAdvice()方法主要根據(jù)AOP配置,將需要回調(diào)的方法封裝成一個(gè)攔截器鏈并返回提供給外部獲取。


package com.tom.spring.formework.aop.support;

import com.tom.spring.formework.aop.GPAopConfig;
import com.tom.spring.formework.aop.aspect.GPAfterReturningAdvice;
import com.tom.spring.formework.aop.aspect.GPAfterThrowingAdvice;
import com.tom.spring.formework.aop.aspect.GPMethodBeforeAdvice;

import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 主要用來解析和封裝AOP配置
 */
public class GPAdvisedSupport {
    private Class targetClass;
    private Object target;
    private Pattern pointCutClassPattern;

    private transient Map<Method, List<Object>> methodCache;

    private GPAopConfig config;

    public GPAdvisedSupport(GPAopConfig config){
        this.config = config;
    }

    public Class getTargetClass() {
        return targetClass;
    }

    public void setTargetClass(Class targetClass) {
        this.targetClass = targetClass;
        parse();
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) throws Exception {
        List<Object> cached = methodCache.get(method);

        //緩存未命中,則進(jìn)行下一步處理
        if (cached == null) {
           Method m = targetClass.getMethod(method.getName(),method.getParameterTypes());
           cached = methodCache.get(m);
            //存入緩存
            this.methodCache.put(m, cached);
        }
        return cached;
    }

    public boolean pointCutMatch(){
        return pointCutClassPattern.matcher(this.targetClass.toString()).matches();
    }

    private void parse(){
        //pointCut表達(dá)式
        String pointCut = config.getPointCut()
                .replaceAll("\\.","\\\\.")
                .replaceAll("\\\\.\\*",".*")
                .replaceAll("\\(","\\\\(")
                .replaceAll("\\)","\\\\)");

        String pointCutForClass = pointCut.substring(0,pointCut.lastIndexOf("\\(") - 4);
        pointCutClassPattern = Pattern.compile("class " + pointCutForClass.substring (pointCutForClass.lastIndexOf(" ")+1));

        methodCache = new HashMap<Method, List<Object>>();
        Pattern pattern = Pattern.compile(pointCut);

        try {
            Class aspectClass = Class.forName(config.getAspectClass());
            Map<String,Method> aspectMethods = new HashMap<String,Method>();
            for (Method m : aspectClass.getMethods()){
                aspectMethods.put(m.getName(),m);
            }

            //在這里得到的方法都是原生方法
            for (Method m : targetClass.getMethods()){

                String methodString = m.toString();
                if(methodString.contains("throws")){
                    methodString = methodString.substring(0,methodString.lastIndexOf("throws")).trim();
                }
                Matcher matcher = pattern.matcher(methodString);
                if(matcher.matches()){
                    //能滿足切面規(guī)則的類,添加到AOP配置中
                    List<Object> advices = new LinkedList<Object>();
                    //前置通知
                    if(!(null == config.getAspectBefore() || "".equals(config.getAspectBefore().trim()))) {
                        advices.add(new GPMethodBeforeAdvice(aspectMethods.get (config.getAspectBefore()), aspectClass.newInstance()));
                    }
                    //后置通知
                    if(!(null == config.getAspectAfter() || "".equals(config.getAspectAfter(). trim()))) {
                        advices.add(new GPAfterReturningAdvice(aspectMethods.get (config.getAspectAfter()), aspectClass.newInstance()));
                    }
                    //異常通知
                    if(!(null == config.getAspectAfterThrow() || "".equals(config.getAspectAfterThrow().trim()))) {
                        GPAfterThrowingAdvice afterThrowingAdvice = new GPAfterThrowingAdvice (aspectMethods.get(config.getAspectAfterThrow()), aspectClass.newInstance());
                        afterThrowingAdvice.setThrowingName(config.getAspectAfterThrowingName());
                        advices.add(afterThrowingAdvice);
                    }
                    methodCache.put(m,advices);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

3.5 GPAopProxy

GPAopProxy是代理工廠的頂層接口,其子類主要有兩個(gè):GPCglibAopProxy和GPJdkDynamicAopProxy,分別實(shí)現(xiàn)CGlib代理和JDK Proxy代理。


package com.tom.spring.formework.aop;
/**
 * 代理工廠的頂層接口,提供獲取代理對(duì)象的頂層入口 
 */
//默認(rèn)就用JDK動(dòng)態(tài)代理
public interface GPAopProxy {
//獲得一個(gè)代理對(duì)象
    Object getProxy();
//通過自定義類加載器獲得一個(gè)代理對(duì)象
    Object getProxy(ClassLoader classLoader);
}

3.6 GPCglibAopProxy

本文未實(shí)現(xiàn)CglibAopProxy,感興趣的“小伙伴”可以自行嘗試。


package com.tom.spring.formework.aop;

import com.tom.spring.formework.aop.support.GPAdvisedSupport;

/**
 * 使用CGlib API生成代理類,在此不舉例
 * 感興趣的“小伙伴”可以自行實(shí)現(xiàn)
 */
public class GPCglibAopProxy implements GPAopProxy {
    private GPAdvisedSupport config;

    public GPCglibAopProxy(GPAdvisedSupport config){
        this.config = config;
    }

    @Override
    public Object getProxy() {
        return null;
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return null;
    }
}

3.7 GPJdkDynamicAopProxy

下面來看GPJdkDynamicAopProxy的實(shí)現(xiàn),主要功能在invoke()方法中。從代碼量來看其實(shí)不多,主要是調(diào)用了GPAdvisedSupport的getInterceptorsAndDynamicInterceptionAdvice()方法獲得攔截器鏈。在目標(biāo)類中,每一個(gè)被增強(qiáng)的目標(biāo)方法都對(duì)應(yīng)一個(gè)攔截器鏈。


package com.tom.spring.formework.aop;

import com.tom.spring.formework.aop.intercept.GPMethodInvocation;
import com.tom.spring.formework.aop.support.GPAdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 使用JDK Proxy API生成代理類
 */
public class GPJdkDynamicAopProxy implements GPAopProxy,InvocationHandler {
    private GPAdvisedSupport config;

    public GPJdkDynamicAopProxy(GPAdvisedSupport config){
        this.config = config;
    }

    //把原生的對(duì)象傳進(jìn)來
    public Object getProxy(){
        return getProxy(this.config.getTargetClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader,this.config.getTargetClass().getInterfaces(),this);
    }

    //invoke()方法是執(zhí)行代理的關(guān)鍵入口
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//將每一個(gè)JoinPoint也就是被代理的業(yè)務(wù)方法(Method)封裝成一個(gè)攔截器,組合成一個(gè)攔截器鏈
        List<Object> interceptorsAndDynamicMethodMatchers = config.getInterceptorsAndDynamicInterceptionAdvice(method,this.config.getTargetClass());
//交給攔截器鏈MethodInvocation的proceed()方法執(zhí)行
        GPMethodInvocation invocation = new GPMethodInvocation(proxy,this.config.getTarget(), method,args,this.config.getTargetClass(),interceptorsAndDynamicMethodMatchers);
        return invocation.proceed();
    }
}

從代碼中可以看出,從GPAdvisedSupport中獲得的攔截器鏈又被當(dāng)作參數(shù)傳入GPMethodInvocation的構(gòu)造方法中。那么GPMethodInvocation中到底又對(duì)方法鏈做了什么呢?

3.8 GPMethodInvocation

GPMethodInvocation的代碼如下:


package com.tom.spring.formework.aop.intercept;

import com.tom.spring.formework.aop.aspect.GPJoinPoint;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 執(zhí)行攔截器鏈,相當(dāng)于Spring中ReflectiveMethodInvocation的功能
 */
public class GPMethodInvocation implements GPJoinPoint {

    private Object proxy; //代理對(duì)象
    private Method method; //代理的目標(biāo)方法
    private Object target; //代理的目標(biāo)對(duì)象
    private Class<?> targetClass; //代理的目標(biāo)類
    private Object[] arguments; //代理的方法的實(shí)參列表
    private List<Object> interceptorsAndDynamicMethodMatchers; //回調(diào)方法鏈

//保存自定義屬性
private Map<String, Object> userAttributes;


    private int currentInterceptorIndex = -1;

    public GPMethodInvocation(Object proxy, Object target, Method method, Object[] arguments,
                              Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
        this.proxy = proxy;
        this.target = target;
        this.targetClass = targetClass;
        this.method = method;
        this.arguments = arguments;
        this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
    }

    public Object proceed() throws Throwable {
//如果Interceptor執(zhí)行完了,則執(zhí)行joinPoint
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return this.method.invoke(this.target,this.arguments);
        }
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
//如果要?jiǎng)討B(tài)匹配joinPoint
if (interceptorOrInterceptionAdvice instanceof GPMethodInterceptor) {
            GPMethodInterceptor mi = (GPMethodInterceptor) interceptorOrInterceptionAdvice;
            return mi.invoke(this);
        } else {
//執(zhí)行當(dāng)前Intercetpor

            return proceed();
        }

    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public Object[] getArguments() {
        return this.arguments;
    }

    @Override
    public Object getThis() {
        return this.target;
    }

public void setUserAttribute(String key, Object value) {
      if (value != null) {
          if (this.userAttributes == null) {
              this.userAttributes = new HashMap<String,Object>();
          }
          this.userAttributes.put(key, value);
      }
      else {
          if (this.userAttributes != null) {
              this.userAttributes.remove(key);
          }
      }
  }


  public Object getUserAttribute(String key) {
      return (this.userAttributes != null ? this.userAttributes.get(key) : null);
  }

}

從代碼中可以看出,proceed()方法才是MethodInvocation的關(guān)鍵所在。在proceed()中,先進(jìn)行判斷,如果攔截器鏈為空,則說明目標(biāo)方法無須增強(qiáng),直接調(diào)用目標(biāo)方法并返回。如果攔截器鏈不為空,則將攔截器鏈中的方法按順序執(zhí)行,直到攔截器鏈中所有方法全部執(zhí)行完畢。

4 設(shè)計(jì)AOP基礎(chǔ)實(shí)現(xiàn)

4.1 GPAdvice

GPAdvice作為所有回調(diào)通知的頂層接口設(shè)計(jì),在Mini版本中為了盡量和原生Spring保持一致,只是被設(shè)計(jì)成了一種規(guī)范,并沒有實(shí)現(xiàn)任何功能。


/**
 * 回調(diào)通知頂層接口
 */
public interface GPAdvice {

}

4.2 GPAbstractAspectJAdvice

使用模板模式設(shè)計(jì)GPAbstractAspectJAdvice類,封裝攔截器回調(diào)的通用邏輯,主要封裝反射動(dòng)態(tài)調(diào)用方法,其子類只需要控制調(diào)用順序即可。


package com.tom.spring.formework.aop.aspect;

import java.lang.reflect.Method;

/**
 * 封裝攔截器回調(diào)的通用邏輯,在Mini版本中主要封裝了反射動(dòng)態(tài)調(diào)用方法
 */
public abstract class GPAbstractAspectJAdvice implements GPAdvice {

    private Method aspectMethod;
    private Object aspectTarget;

    public GPAbstractAspectJAdvice(
            Method aspectMethod, Object aspectTarget) {
            this.aspectMethod = aspectMethod;
            this.aspectTarget = aspectTarget;
    }

    //反射動(dòng)態(tài)調(diào)用方法
    protected Object invokeAdviceMethod(GPJoinPoint joinPoint,Object returnValue,Throwable ex)
            throws Throwable {
        Class<?> [] paramsTypes = this.aspectMethod.getParameterTypes();
        if(null == paramsTypes || paramsTypes.length == 0) {
            return this.aspectMethod.invoke(aspectTarget);
        }else {
            Object[] args = new Object[paramsTypes.length];
            for (int i = 0; i < paramsTypes.length; i++) {
                if(paramsTypes[i] == GPJoinPoint.class){
                    args[i] = joinPoint;
                }else if(paramsTypes[i] == Throwable.class){
                    args[i] = ex;
                }else if(paramsTypes[i] == Object.class){
                    args[i] = returnValue;
                }
            }
            return this.aspectMethod.invoke(aspectTarget,args);
        }
    }
}

4.3 GPMethodBeforeAdvice

GPMethodBeforeAdvice繼承GPAbstractAspectJAdvice,實(shí)現(xiàn)GPAdvice和GPMethodInterceptor接口,在invoke()中控制前置通知的調(diào)用順序。


package com.tom.spring.formework.aop.aspect;

import com.tom.spring.formework.aop.intercept.GPMethodInterceptor;
import com.tom.spring.formework.aop.intercept.GPMethodInvocation;

import java.lang.reflect.Method;

/**
 * 前置通知具體實(shí)現(xiàn)
 */
public class GPMethodBeforeAdvice extends GPAbstractAspectJAdvice implements GPAdvice, GPMethodInterceptor {

    private GPJoinPoint joinPoint;

    public GPMethodBeforeAdvice(Method aspectMethod, Object target) {
        super(aspectMethod, target);
    }

    public void before(Method method, Object[] args, Object target) throws Throwable {
        invokeAdviceMethod(this.joinPoint,null,null);
    }

    public Object invoke(GPMethodInvocation mi) throws Throwable {
        this.joinPoint = mi;
        this.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        return mi.proceed();
    }
}

4.4 GPAfterReturningAdvice

GPAfterReturningAdvice繼承GPAbstractAspectJAdvice,實(shí)現(xiàn)GPAdvice和GPMethodInterceptor接口,在invoke()中控制后置通知的調(diào)用順序。


package com.tom.spring.formework.aop.aspect;

import com.tom.spring.formework.aop.intercept.GPMethodInterceptor;
import com.tom.spring.formework.aop.intercept.GPMethodInvocation;

import java.lang.reflect.Method;

/**
 * 后置通知具體實(shí)現(xiàn)
 */
public class GPAfterReturningAdvice extends GPAbstractAspectJAdvice implements GPAdvice, GPMethodInterceptor {

    private GPJoinPoint joinPoint;
    public GPAfterReturningAdvice(Method aspectMethod, Object target) {
        super(aspectMethod, target);
    }

    @Override
    public Object invoke(GPMethodInvocation mi) throws Throwable {
        Object retVal = mi.proceed();
        this.joinPoint = mi;
        this.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }

    public void afterReturning(Object returnValue, Method method, Object[] args,Object target) throws Throwable{
        invokeAdviceMethod(joinPoint,returnValue,null);
    }

}

4.5 GPAfterThrowingAdvice

GPAfterThrowingAdvice繼承GPAbstractAspectJAdvice,實(shí)現(xiàn)GPAdvice和GPMethodInterceptor接口,在invoke()中控制異常通知的調(diào)用順序。


package com.tom.spring.formework.aop.aspect;

import com.tom.spring.formework.aop.intercept.GPMethodInterceptor;
import com.tom.spring.formework.aop.intercept.GPMethodInvocation;

import java.lang.reflect.Method;

/**
 * 異常通知具體實(shí)現(xiàn)
 */
public class GPAfterThrowingAdvice extends GPAbstractAspectJAdvice implements GPAdvice, GPMethodInterceptor {

    private String throwingName;
    private GPMethodInvocation mi;

    public GPAfterThrowingAdvice(Method aspectMethod, Object target) {
        super(aspectMethod, target);
    }

    public void setThrowingName(String name) {
        this.throwingName = name;
    }

    @Override
    public Object invoke(GPMethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();
        }catch (Throwable ex) {
            invokeAdviceMethod(mi,null,ex.getCause());
            throw ex;
        }
    }
}

感興趣的“小伙伴”可以參看Spring源碼,自行實(shí)現(xiàn)環(huán)繞通知的調(diào)用邏輯。

4.6 接入getBean()方法

在上面的代碼中,我們已經(jīng)完成了Spring AOP模塊的核心功能,那么接下如何集成到IoC容器中去呢?找到GPApplicationContext的getBean()方法,我們知道getBean()中負(fù)責(zé)Bean初始化的方法其實(shí)就是instantiateBean(),在初始化時(shí)就可以確定是否返回原生Bean或Proxy Bean。代碼實(shí)現(xiàn)如下:


//傳一個(gè)BeanDefinition,返回一個(gè)實(shí)例Bean
private Object instantiateBean(GPBeanDefinition beanDefinition){
    Object instance = null;
    String className = beanDefinition.getBeanClassName();
    try{

        //因?yàn)楦鶕?jù)Class才能確定一個(gè)類是否有實(shí)例
        if(this.singletonBeanCacheMap.containsKey(className)){
            instance = this.singletonBeanCacheMap.get(className);
        }else{
            Class<?> clazz = Class.forName(className);
            instance = clazz.newInstance();

            GPAdvisedSupport config = instantionAopConfig(beanDefinition);
            config.setTargetClass(clazz);
            config.setTarget(instance);

            if(config.pointCutMatch()) {
                instance = createProxy(config).getProxy();
            }
          this.factoryBeanObjectCache.put(className,instance);
            this.singletonBeanCacheMap.put(beanDefinition.getFactoryBeanName(),instance);
        }

        return instance;
    }catch (Exception e){
        e.printStackTrace();
    }

    return null;
}

private GPAdvisedSupport instantionAopConfig(GPBeanDefinition beanDefinition) throws  Exception{

    GPAopConfig config = new GPAopConfig();
    config.setPointCut(reader.getConfig().getProperty("pointCut"));
    config.setAspectClass(reader.getConfig().getProperty("aspectClass"));
    config.setAspectBefore(reader.getConfig().getProperty("aspectBefore"));
    config.setAspectAfter(reader.getConfig().getProperty("aspectAfter"));
    config.setAspectAfterThrow(reader.getConfig().getProperty("aspectAfterThrow"));
    config.setAspectAfterThrowingName(reader.getConfig().getProperty("aspectAfterThrowingName"));

    return new GPAdvisedSupport(config);
}

private GPAopProxy createProxy(GPAdvisedSupport config) {
    Class targetClass = config.getTargetClass();
    if (targetClass.getInterfaces().length > 0) {
        return new GPJdkDynamicAopProxy(config);
    }
    return new GPCglibAopProxy(config);
}

從上面的代碼中可以看出,在instantiateBean()方法中調(diào)用createProxy()決定代理工廠的調(diào)用策略,然后調(diào)用代理工廠的proxy()方法創(chuàng)建代理對(duì)象。最終代理對(duì)象將被封裝到BeanWrapper中并保存到IoC容器。

5 織入業(yè)務(wù)代碼

通過前面的代碼編寫,所有的核心模塊和底層邏輯都已經(jīng)實(shí)現(xiàn),“萬事俱備,只欠東風(fēng)?!苯酉聛恚撌恰耙娮C奇跡的時(shí)刻了”。我們來織入業(yè)務(wù)代碼,做一個(gè)測試。創(chuàng)建LogAspect類,實(shí)現(xiàn)對(duì)業(yè)務(wù)方法的監(jiān)控。主要記錄目標(biāo)方法的調(diào)用日志,獲取目標(biāo)方法名、實(shí)參列表、每次調(diào)用所消耗的時(shí)間。

5.1 LogAspect

LogAspect的代碼如下:


package com.tom.spring.demo.aspect;

import com.tom.spring.formework.aop.aspect.GPJoinPoint;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * 定義一個(gè)織入的切面邏輯,也就是要針對(duì)目標(biāo)代理對(duì)象增強(qiáng)的邏輯
 * 本類主要完成對(duì)方法調(diào)用的監(jiān)控,監(jiān)聽目標(biāo)方法每次執(zhí)行所消耗的時(shí)間
 */
@Slf4j
public class LogAspect {

    //在調(diào)用一個(gè)方法之前,執(zhí)行before()方法
    public void before(GPJoinPoint joinPoint){
        joinPoint.setUserAttribute("startTime_" + joinPoint.getMethod().getName(),System.currentTimeMillis());
        //這個(gè)方法中的邏輯是由我們自己寫的
        log.info("Invoker Before Method!!!" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
    }

    //在調(diào)用一個(gè)方法之后,執(zhí)行after()方法
    public void after(GPJoinPoint joinPoint){
        log.info("Invoker After Method!!!" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
        long startTime = (Long) joinPoint.getUserAttribute("startTime_" + joinPoint.getMethod().getName());
        long endTime = System.currentTimeMillis();
        System.out.println("use time :" + (endTime - startTime));
    }

    public void afterThrowing(GPJoinPoint joinPoint, Throwable ex){
        log.info("出現(xiàn)異常" +
                "\nTargetObject:" +  joinPoint.getThis() +
                "\nArgs:" + Arrays.toString(joinPoint.getArguments()) +
                "\nThrows:" + ex.getMessage());
    }
}

通過上面的代碼可以發(fā)現(xiàn),每一個(gè)回調(diào)方法都加了一個(gè)參數(shù)GPJoinPoint,還記得GPJoinPoint為何物嗎?事實(shí)上,GPMethodInvocation就是GPJoinPoint的實(shí)現(xiàn)類。而GPMethodInvocation又是在GPJdkDynamicAopPorxy的invoke()方法中實(shí)例化的,即每個(gè)被代理對(duì)象的業(yè)務(wù)方法會(huì)對(duì)應(yīng)一個(gè)GPMethodInvocation實(shí)例。也就是說,MethodInvocation的生命周期是被代理對(duì)象中業(yè)務(wù)方法的生命周期的對(duì)應(yīng)。前面我們已經(jīng)了解,調(diào)用GPJoinPoint的setUserAttribute()方法可以在GPJoinPoint中自定義屬性,調(diào)用getUserAttribute()方法可以獲取自定義屬性的值。
在LogAspect的before()方法中,在GPJoinPoint中設(shè)置了startTime并賦值為系統(tǒng)時(shí)間,即記錄方法開始調(diào)用時(shí)間到MethodInvocation的上下文。在LogAspect的after()方法中獲取startTime,再次獲取的系統(tǒng)時(shí)間保存到endTime。在AOP攔截器鏈回調(diào)中,before()方法肯定在after()方法之前調(diào)用,因此兩次獲取的系統(tǒng)時(shí)間會(huì)形成一個(gè)時(shí)間差,這個(gè)時(shí)間差就是業(yè)務(wù)方法執(zhí)行所消耗的時(shí)間。通過這個(gè)時(shí)間差,就可以判斷業(yè)務(wù)方法在單位時(shí)間內(nèi)的性能消耗,是不是設(shè)計(jì)得非常巧妙?事實(shí)上,市面上幾乎所有的系統(tǒng)監(jiān)控框架都是基于這樣一種思想來實(shí)現(xiàn)的,可以高度解耦并減少代碼侵入。

5.2 IModifyService

為了演示異?;卣{(diào)通知,我們給之前定義的IModifyService接口的add()方法添加了拋出異常的功能,看下面的代碼實(shí)現(xiàn):


package com.tom.spring.demo.service;

/**
 * 增、刪、改業(yè)務(wù)
  */
public interface IModifyService {

   /**
    * 增加
    */
   String add(String name, String addr) throws Exception;
   
   /**
    * 修改
    */
   String edit(Integer id, String name);
   
   /**
    * 刪除
    */
   String remove(Integer id);
   
}

5.3 ModifyService

ModifyService的代碼如下:


package com.tom.spring.demo.service.impl;

import com.tom.spring.demo.service.IModifyService;
import com.tom.spring.formework.annotation.GPService;

/**
 * 增、刪、改業(yè)務(wù)
 */
@GPService
public class ModifyService implements IModifyService {

   /**
    * 增加
    */
   public String add(String name,String addr) throws Exception {
      throw new Exception("故意拋出異常,測試切面通知是否生效");
//    return "modifyService add,name=" + name + ",addr=" + addr;
   }

   /**
    * 修改
    */
   public String edit(Integer id,String name) {
      return "modifyService edit,id=" + id + ",name=" + name;
   }

   /**
    * 刪除
    */
   public String remove(Integer id) {
      return "modifyService id=" + id;
   }
}

6 運(yùn)行效果演示

在瀏覽器中輸入 http://localhost/web/add.json?name=Tom&addr=HunanChangsha ,就可以直觀明了地看到Service層拋出的異常信息,如下圖所示。

file

控制臺(tái)輸出如下圖所示。

file

通過控制臺(tái)輸出,可以看到異常通知成功捕獲異常信息,觸發(fā)了GPMethodBeforeAdvice 和GPAfterThrowingAdvice,而并未觸發(fā)GPAfterReturningAdvice,符合我們的預(yù)期。
下面再做一個(gè)測試,輸入 http://localhost/web/query.json?name=Tom ,結(jié)果如下圖所示:

file

控制臺(tái)輸出如下圖所示:

file

通過控制臺(tái)輸出可以看到,分別捕獲了前置通知、后置通知,并打印了相關(guān)信息,符合我們的預(yù)期。

至此AOP模塊大功告成,是不是有一種小小的成就感,躍躍欲試?在整個(gè)Mini版本實(shí)現(xiàn)中有些細(xì)節(jié)沒有過多考慮,更多的是希望給“小伙伴們”提供一種學(xué)習(xí)源碼的思路。手寫源碼不是為了重復(fù)造輪子,也不是為了裝“高大上”,其實(shí)只是我們推薦給大家的一種學(xué)習(xí)方式。
關(guān)注『 Tom彈架構(gòu) 』回復(fù)“Spring”可獲取完整源碼。

本文為“Tom彈架構(gòu)”原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處。技術(shù)在于分享,我分享我快樂!如果您有任何建議也可留言評(píng)論或私信,您的支持是我堅(jiān)持創(chuàng)作的動(dòng)力。關(guān)注『 Tom彈架構(gòu) 』可獲取更多技術(shù)干貨!

原創(chuàng)不易,堅(jiān)持很酷,都看到這里了,小伙伴記得點(diǎn)贊、收藏、在看,一鍵三連加關(guān)注!如果你覺得內(nèi)容太干,可以分享轉(zhuǎn)發(fā)給朋友滋潤滋潤!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容