1. 程式人生 > >Mybatis框架(8)---Mybatis外掛原理

Mybatis框架(8)---Mybatis外掛原理

Mybatis外掛原理

在實際開發過程中,我們經常使用的Mybaits外掛就是分頁外掛了,通過分頁外掛我們可以在不用寫count語句和limit的情況下就可以獲取分頁後的資料,給我們開發帶來很大

的便利。除了分頁,外掛使用場景主要還有更新資料庫的通用欄位,分庫分表,加解密等的處理。

這篇部落格主要講Mybatis外掛原理,下一篇部落格會設計一個Mybatis外掛實現的功能就是每當新增資料的時候不用資料庫自增ID而是通過該外掛生成雪花ID,作為每條資料的主鍵。

一、JDK動態代理+責任鏈設計模式

Mybatis的外掛其實就是個攔截器功能。它利用JDK動態代理和責任鏈設計模式的綜合運用。採用責任鏈模式,通過動態代理組織多個攔截器,通過這些攔截器你可以做一些

你想做的事。所以在講Mybatis攔截器之前我們先說說JDK動態代理+責任鏈設計模式。有關JDK動態代理的原理,可以參考我之前寫的一篇部落格:【java設計模式】---代理模式

1、JDK動態代理案例

public class MyProxy {
    /**
     * 一個介面
     */
    public interface HelloService{
        void sayHello();
    }
    /**
     * 目標類實現介面
     */
    static class HelloServiceImpl implements HelloService{

        @Override
        public void sayHello() {
            System.out.println("sayHello......");
        }
    }
    /**
     * 自定義代理類需要實現InvocationHandler介面
     */
    static  class HWInvocationHandler implements InvocationHandler {
        /**
         * 目標物件
         */
        private Object target;

        public HWInvocationHandler(Object target){
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("------插入前置通知程式碼-------------");
            //執行相應的目標方法
            Object rs = method.invoke(target,args);
            System.out.println("------插入後置處理程式碼-------------");
            return rs;
        }

        public static Object wrap(Object target) {
            return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(),new HWInvocationHandler(target));
        }
    }
    public static void main(String[] args)  {
        HelloService proxyService = (HelloService) HWInvocationHandler.wrap(new HelloServiceImpl());
        proxyService.sayHello();
    }
}

執行結果

------插入前置通知程式碼-------------
sayHello......
------插入後置處理程式碼-------------

2、優化

上面代理的功能是實現了,但是有個很明顯的缺陷,就是HWInvocationHandler是動態代理類,也可以理解成是個工具類,我們不可能會把業務程式碼寫到寫到到invoke方法裡,

不符合面向物件的思想,可以抽象一下處理。可以設計一個Interceptor介面,需要做什麼攔截處理實現介面就行了。

public interface Interceptor {
    /**
     * 具體攔截處理
     */
    void intercept();
}

intercept() 方法就可以處理各種前期準備了

public class LogInterceptor implements Interceptor {
    @Override
    public void intercept() {
        System.out.println("------插入前置通知程式碼-------------");
    }
}

public class TransactionInterceptor implements Interceptor {
    @Override
    public void intercept() {
        System.out.println("------插入後置處理程式碼-------------");
    }
}

代理物件也做一下修改

public class HWInvocationHandler implements InvocationHandler {

    private Object target;

    private List<Interceptor> interceptorList = new ArrayList<>();

    public TargetProxy(Object target,List<Interceptor> interceptorList) {
        this.target = target;
        this.interceptorList = interceptorList;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       //處理多個攔截器
        for (Interceptor interceptor : interceptorList) {
            interceptor.intercept();
        }
        return method.invoke(target, args);
    }

    public static Object wrap(Object target,List<Interceptor> interceptorList) {
        HWInvocationHandler targetProxy = new HWInvocationHandler(target, interceptorList);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),targetProxy);
    }
}

現在可以根據需要動態的新增攔截器了,在每次執行業務程式碼sayHello()之前都會攔截,看起來高階一點,來測試一下

public class Test {
    public static void main(String[] args) {
        List<Interceptor> interceptorList = new ArrayList<>();
        interceptorList.add(new LogInterceptor());
        interceptorList.add(new TransactionInterceptor());

        HelloService target = new HelloServiceImpl();
        Target targetProxy = (Target) TargetProxy.wrap(target,interceptorList);
        targetProxy.sayHello();
    }
}

執行結果

------插入前置通知程式碼-------------
------插入後置處理程式碼-------------
sayHello......

3、再優化

上面的動態代理確實可以把代理類中的業務邏輯抽離出來,但是我們注意到,只有前置代理,無法做到前後代理,所以還需要在優化下。所以需要做更一步的抽象,

把攔截物件資訊進行封裝,作為攔截器攔截方法的引數,把攔截目標物件真正的執行方法放到Interceptor中完成,這樣就可以實現前後攔截,並且還能對攔截

物件的引數等做修改。設計一個Invocation 物件

public class Invocation {

    /**
     * 目標物件
     */
    private Object target;
    /**
     * 執行的方法
     */
    private Method method;
    /**
     * 方法的引數
     */
    private Object[] args;
    
    //省略getset
    public Invocation(Object target, Method method, Object[] args) {
        this.target = target;
        this.method = method;
        this.args = args;
    }

    /**
     * 執行目標物件的方法
     */
    public Object process() throws Exception{
       return method.invoke(target,args);
    }
}

Interceptor攔截介面做修改

public interface Interceptor {
    /**
     * 具體攔截處理
     */
    Object intercept(Invocation invocation) throws Exception;
}

Interceptor實現類

public class TransactionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Exception{
        System.out.println("------插入前置通知程式碼-------------");
        Object result = invocation.process();
        System.out.println("------插入後置處理程式碼-------------");
        return result;
    }
}

Invocation 類就是被代理物件的封裝,也就是要攔截的真正物件。HWInvocationHandler修改如下:

public class HWInvocationHandler implements InvocationHandler {

    private Object target;

    private Interceptor interceptor;

    public TargetProxy(Object target,Interceptor interceptor) {
        this.target = target;
        this.interceptor = interceptor;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Invocation invocation = new Invocation(target,method,args);
        return interceptor.intercept(invocation);
    }

    public static Object wrap(Object target,Interceptor interceptor) {
        HWInvocationHandler targetProxy = new HWInvocationHandler(target, interceptor);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),targetProxy);
    }
}

測試類

public class Test {
    public static void main(String[] args) {
        HelloService target = new HelloServiceImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        HelloService targetProxy = (Target) TargetProxy.wrap(target,transactionInterceptor);
        targetProxy.sayHello();
    }
}

執行結果

------插入前置通知程式碼-------------
sayHello......
------插入後置處理程式碼-------------

4、再再優化

上面這樣就能實現前後攔截,並且攔截器能獲取攔截物件資訊。但是測試程式碼的這樣呼叫看著很彆扭,對應目標類來說,只需要瞭解對他插入了什麼攔截就好。

再修改一下,在攔截器增加一個插入目標類的方法。

public interface Interceptor {
    /**
     * 具體攔截處理
     */
    Object intercept(Invocation invocation) throws Exception;

    /**
     *  插入目標類
     */
    Object plugin(Object target);

}

public class TransactionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Exception{
        System.out.println("------插入前置通知程式碼-------------");
        Object result = invocation.process();
        System.out.println("------插入後置處理程式碼-------------");
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return TargetProxy.wrap(target,this);
    }
}

這樣目標類僅僅需要在執行前,插入需要的攔截器就好了,測試程式碼:

public class Test {
    public static void main(String[] args) {
        HelloService target = new HelloServiceImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        //把事務攔截器插入到目標類中
        target = (HelloService) transactionInterceptor.plugin(target);
        target.sayHello();
    }
}

執行結果

------插入前置通知程式碼-------------
sayHello......
------插入後置處理程式碼-------------

5、多個攔截器如何處理

到這裡就差不多完成了,那我們再來思考如果要新增多個攔截器呢,怎麼搞?

public class Test {
    public static void main(String[] args) {
        HelloService target = new HelloServiceImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        target = (HelloService) transactionInterceptor.plugin(target);
        LogInterceptor logInterceptor = new LogInterceptor();
        target = (HelloService)logInterceptor.plugin(target);
        target.sayHello();
    }
}

執行結果

------插入前置通知程式碼-------------
------插入前置通知程式碼-------------
sayHello......
------插入後置處理程式碼-------------
------插入後置處理程式碼-------------

6、責任鏈設計模式

其實上面已經實現的沒問題了,只是還差那麼一點點,新增多個攔截器的時候不太美觀,讓我們再次利用面向物件思想封裝一下。我們設計一個InterceptorChain 攔截器鏈類

public class InterceptorChain {

    private List<Interceptor> interceptorList = new ArrayList<>();

    /**
     * 插入所有攔截器
     */
    public Object pluginAll(Object target) {
        for (Interceptor interceptor : interceptorList) {
            target = interceptor.plugin(target);
        }
        return target;
    }

    public void addInterceptor(Interceptor interceptor) {
        interceptorList.add(interceptor);
    }
    /**
     * 返回一個不可修改集合,只能通過addInterceptor方法新增
     * 這樣控制權就在自己手裡
     */
    public List<Interceptor> getInterceptorList() {
        return Collections.unmodifiableList(interceptorList);
    }
}

其實就是通過pluginAll() 方法包一層把所有的攔截器插入到目標類去而已。測試程式碼:

public class Test {

    public static void main(String[] args) {
        HelloService target = new HelloServiceImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        LogInterceptor logInterceptor = new LogInterceptor();
        InterceptorChain interceptorChain = new InterceptorChain();
        interceptorChain.addInterceptor(transactionInterceptor);
        interceptorChain.addInterceptor(logInterceptor);
        target = (Target) interceptorChain.pluginAll(target);
        target.sayHello();
    }
}

這裡展示的是JDK動態代理+責任鏈設計模式,那麼Mybatis攔截器就是基於該組合進行開發。


二、Mybatis Plugin 外掛概念

1、原理

Mybatis的攔截器實現機制跟上面最後優化後的程式碼非常的相似。它也有個代理類Plugin(就是上面的HWInvocationHandler)這個類同樣也會實現了InvocationHandler介面,

當我們呼叫ParameterHandler,ResultSetHandler,StatementHandler,Executor的物件的時候,,就會執行Plugin的invoke方法,Plugin在invoke方法中根據

@Intercepts的配置資訊(方法名,引數等)動態判斷是否需要攔截該方法.再然後使用需要攔截的方法Method封裝成Invocation,並呼叫Interceptor的proceed方法。

這樣我們就達到了攔截目標方法的結果。例如Executor的執行大概是這樣的流程:

攔截器代理類物件->攔截器->目標方法
Executor.Method->Plugin.invoke->Interceptor.intercept->Invocation.proceed->method.invoke。

2、如何自定義攔截器?

1) Interceptor介面

首先Mybatis官方早就想到我們開發會有這樣的需求,所以開放了一個org.apacheibatis.plugin.Interceptor這樣一個介面。這個介面就是和上面Interceptor性質是一樣的

public interface Interceptor {
  //當plugin函式返回代理,就可以對其中的方法進行攔截來呼叫intercept方法
  Object intercept(Invocation invocation) throws Throwable;
  //plugin方法是攔截器用於封裝目標物件的,通過該方法我們可以返回目標物件本身,也可以返回一個它的代理。
  Object plugin(Object target);
 //在Mybatis配置檔案中指定一些屬性
  void setProperties(Properties properties);
}

2)自定義攔截器

這裡的ExamplePlugin和上面的LogInterceptor和TransactionInterceptor性質是一樣的

@Intercepts({@Signature( type= Executor.class,  method = "update", args ={MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
  public Object intercept(Invocation invocation) throws Throwable {
    return invocation.proceed();
  }
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  public void setProperties(Properties properties) {
  }
}

3)、全域性xml配置

最後如果你使用的是Mybatis.xml也就是Mybatis本身單獨的配置,你可以需要在這裡配置相應的攔截器名字等。

如果你使用的是spring管理的Mybatis,那麼你需要在Spring配置檔案裡面配置註冊相應的攔截器。

這樣一個自定義mybatis外掛流程大致就是這樣了。

3、Mybatis四大介面

竟然Mybatis是對四大介面進行攔截的,那我們要先要知道Mybatis的四大介面物件 Executor, StatementHandle, ResultSetHandler, ParameterHandler

1.Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) MyBatis的執行器,用於執行增刪改查操作;
2.ParameterHandler (getParameterObject, setParameters) 處理SQL的引數物件;
3.ResultSetHandler (handleResultSets, handleOutputParameters) 處理SQL的返回結果集;
4.StatementHandler (prepare, parameterize, batch, update, query) 攔截Sql語法構建的處理

上圖Mybatis框架的整個執行過程。


三、Mybatis Plugin 外掛原始碼

經過上面的分析,再去看Mybastis Plugin 原始碼的時候就很輕鬆了。

這幾個也就對應上面的幾個,只不過添加了註解,來判斷是否攔截指定方法。

1、攔截器鏈InterceptorChain

public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  public Object pluginAll(Object target) {
    //迴圈呼叫每個Interceptor.plugin方法
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }
}

這個就和我們上面實現的是一樣的。定義了攔截器鏈

2、Configuration

通過初始化配置檔案把所有的攔截器新增到攔截器鏈中。

public class Configuration {

    protected final InterceptorChain interceptorChain = new InterceptorChain();
    //建立引數處理器
  public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    //建立ParameterHandler
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    //外掛在這裡插入
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  }

  //建立結果集處理器
  public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    //建立DefaultResultSetHandler
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    //外掛在這裡插入
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }

  //建立語句處理器
  public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    //建立路由選擇語句處理器
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    //外掛在這裡插入
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

  public Executor newExecutor(Transaction transaction) {
    return newExecutor(transaction, defaultExecutorType);
  }

  //產生執行器
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    //這句再做一下保護,囧,防止粗心大意的人將defaultExecutorType設成null?
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    //然後就是簡單的3個分支,產生3種執行器BatchExecutor/ReuseExecutor/SimpleExecutor
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    //如果要求快取,生成另一種CachingExecutor(預設就是有快取),裝飾者模式,所以預設都是返回CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //此處呼叫外掛,通過外掛可以改變Executor行為
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
}

從程式碼可以看出Mybatis 在例項化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大介面物件的時候呼叫interceptorChain.pluginAll()方法插入

進去的。其實就是迴圈執行攔截器鏈所有的攔截器的plugin() 方法,mybatis官方推薦的plugin方法是Plugin.wrap() 方法,這個類就是我們上面的TargetProxy類。

3、Plugin

這裡的Plugin就是我們上面的自定義代理類TargetProxy類

public class Plugin implements InvocationHandler {

    public static Object wrap(Object target, Interceptor interceptor) {
    //從攔截器的註解中獲取攔截的類名和方法資訊
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    //取得要改變行為的類(ParameterHandler|ResultSetHandler|StatementHandler|Executor)
    Class<?> type = target.getClass();
    //取得介面
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //產生代理,是Interceptor註解的介面的實現類才會產生代理
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
    
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //獲取需要攔截的方法
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      //是Interceptor實現類註解的方法才會攔截處理
      if (methods != null && methods.contains(method)) {
        //呼叫Interceptor.intercept,也即插入了我們自己的邏輯
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //最後還是執行原來邏輯
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
    
    //取得簽名Map,就是獲取Interceptor實現類上面的註解,要攔截的是那個類(Executor,ParameterHandler,   ResultSetHandler,StatementHandler)的那個方法
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    //取Intercepts註解,例子可參見ExamplePlugin.java
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    //必須得有Intercepts註解,沒有報錯
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    //value是陣列型,Signature的陣列
    Signature[] sigs = interceptsAnnotation.value();
    //每個class裡有多個Method需要被攔截,所以這麼定義
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
        Method method = sig.type().getMethod(sig.method(), sig.args());
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }
    
    //取得介面
  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        //攔截其他的無效
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }
}

4、Interceptor介面

public interface Interceptor {

  //攔截
  Object intercept(Invocation invocation) throws Throwable;
  //插入
  Object plugin(Object target);
  //設定屬性(擴充套件)
  void setProperties(Properties properties);

}

思路 這麼下來思路就很清晰了,我們通過實現Interceptor類實現自定義攔截器,然後把它放入InterceptorChain(攔截器鏈)中,然後通過JDK動態代理來實現依次攔截處理。


致謝

非常感謝一篇部落格,它講的循序漸進,讓我不僅僅對JDK動態代理+責任鏈模式有更好的理解,而且在程式碼設計上也有很大的啟發,確實受益很大。非常感謝!

Mybatis Plugin 外掛(攔截器)原理分析




 我相信,無論今後的道路多麼坎坷,只要抓住今天,遲早會在奮鬥中嚐到人生的甘甜。抓住人生中的一分一秒,勝過虛度中的一月一年!(6)

<