Mybatis Plugin 插件(攔截器)原理分析

Mybatis Plugin 插件(攔截器)原理分析

引言

最近在看mybatis 源碼,看到了mybatis plugin部分,其實就是利用JDK動態(tài)代理和責任鏈設(shè)計模式的綜合運用。采用責任鏈模式,通過動態(tài)代理組織多個攔截器,通過這些攔截器你可以做一些你想做的事。具體分析從一個普通的需求功能開始:現(xiàn)在要對所有的接口方法做一個日志記錄和接口耗時記錄。

需求分析和功能實現(xiàn)

看到這個需求功能我默默的笑了,這還不簡單,每個方法我都加上不就行了嗎?就這么干,擼起袖子開始噼噼啪啪的敲打著鍵盤,慢慢發(fā)現(xiàn)太特么多方法了,而且還是基本重復的,這樣寫下去不是辦法啊。這么多重復的是不是可以抽取出來呢,要堅持 DRY(Don't repeat yourself)原則。這時候想到了代理設(shè)計模式,靜態(tài)代理模式肯定不行,這么多接口,得寫多少個代理類啊,還是用JDK的動態(tài)代理吧

JDK動態(tài)代理

public interface Target {
    String execute(String name);
}

public class TargetImpl implements Target {
    @Override
    public String execute(String name) {
        System.out.println("execute() "+ name);
        return name;
    }
}

public class TargetProxy implements InvocationHandler {

    private Object target;
    public TargetProxy(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(" 攔截前。。。");
        Object result = method.invoke(target, args);
        System.out.println(" 攔截后。。。");
        return result;
    }

    public static Object wrap(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),new TargetProxy(target));
    }
}

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        //返回的是代理對象,實現(xiàn)了Target接口,
        //實際調(diào)用方法的時候,是調(diào)用TargetProxy的invoke()方法
        Target targetProxy = (Target) TargetProxy.wrap(target);
        targetProxy.execute(" HelloWord ");

    }
}

TargetProxy.wrap(target) 實際返回的對象類似下面這樣,這樣看起來就容易理解點了

public class $Proxy implements Target {

    private InvocationHandler targetProxy
    
    @Override
    public String execute(String name) {
        return targetProxy.invoke();
    }
}

運行結(jié)果:

攔截前。。。
execute()  HelloWord 
 攔截后。。。

嗯,這思路是正確的了。但還是存在問題,execute() 是業(yè)務代碼,我把所有的要攔截處理的邏輯都寫到invoke方法里面了,不符合面向?qū)ο蟮乃枷耄梢猿橄笠幌绿幚???梢栽O(shè)計一個Interceptor接口,需要做什么攔截處理實現(xiàn)接口就行了。

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 TargetProxy 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) {
        TargetProxy targetProxy = new TargetProxy(target, interceptorList);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),targetProxy);
    }
}

現(xiàn)在可以根據(jù)需要動態(tài)的添加攔截器了,在每次執(zhí)行業(yè)務代碼execute(...)之前都會攔截,看起來高級一丟丟了,來測試一下

public class Test {

    public static void main(String[] args) {

        List<Interceptor> interceptorList = new ArrayList<>();
        interceptorList.add(new LogInterceptor());
        interceptorList.add(new TransactionInterceptor());

        Target target = new TargetImpl();
        Target targetProxy = (Target) TargetProxy.wrap(target,interceptorList);
        targetProxy.execute(" HelloWord ");

    }
}

執(zhí)行結(jié)果:

 記錄日志 
 開啟事務 
execute()  HelloWord 

貌似有哪里不太對一樣,按照上面這種我們只能做前置攔截,而且攔截器并不知道攔截對象的信息。應該做更一步的抽象,把攔截對象信息進行封裝,作為攔截器攔截方法的參數(shù),把攔截目標對象真正的執(zhí)行方法放到Interceptor中完成,這樣就可以實現(xiàn)前后攔截,并且還能對攔截對象的參數(shù)等做修改。設(shè)計一個Invocation 對象

public class Invocation {

    /**
     * 目標對象
     */
    private Object target;
    /**
     * 執(zhí)行的方法
     */
    private Method method;
    /**
     * 方法的參數(shù)
     */
    private Object[] args;
    
    //省略getset

    public Invocation(Object target, Method method, Object[] args) {
        this.target = target;
        this.method = method;
        this.args = args;
    }

    /**
     * 執(zhí)行目標對象的方法
     * @return
     * @throws Exception
     */
    public Object process() throws Exception{
       return method.invoke(target,args);
    }
}

攔截接口做修改

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

}

Invocation 類就是被代理對象的封裝,也就是要攔截的真正對象。TargetProxy修改如下:

public class TargetProxy 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) {
        TargetProxy targetProxy = new TargetProxy(target, interceptor);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),targetProxy);
    }
}
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;
    }
}

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        Target targetProxy = (Target) TargetProxy.wrap(target,transactionInterceptor);
        targetProxy.execute(" HelloWord ");

    }
}

運行結(jié)果:

 開啟事務 
execute()  HelloWord 
  提交事務 

這樣就能實現(xiàn)前后攔截,并且攔截器能獲取攔截對象信息,這樣擴展性就好很多了。但是測試例子的這樣調(diào)用看著很別扭,對應目標類來說,只需要了解對他插入了什么攔截就好。再修改一下,在攔截器增加一個插入目標類的方法

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

    /**
     *  插入目標類
     * @param target
     * @return
     */
    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);
    }
}

這樣目標類僅僅需要在執(zhí)行前,插入需要的攔截器就好了,測試代碼:

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        //把事務攔截器插入到目標類中
        target = (Target) transactionInterceptor.plugin(target);
        target.execute(" HelloWord ");

    }
}

運行結(jié)果:

 開啟事務 
execute()  HelloWord 
 提交事務 

到這里就差不多完成了,可能有同學可能會有疑問,那我要添加多個攔截器呢,怎么搞?

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        target = (Target) transactionInterceptor.plugin(target);
        LogInterceptor logInterceptor = new LogInterceptor();
        target = (Target)logInterceptor.plugin(target);
        target.execute(" HelloWord ");

    }
}

運行結(jié)果:

 開始記錄日志 
 開啟事務 
execute()  HelloWord 
 提交事務 
 結(jié)束記錄日志 

其實這就是代理嵌套再代理,下圖是執(zhí)行的時序圖,每個步驟就不做詳細的說明了

時序圖.png

責任鏈

其實上面已經(jīng)實現(xiàn)的沒問題了,只是還差那么一點點,添加多個攔截器的時候不太美觀,讓我們再次利用面向?qū)ο笏枷敕庋b一下。我們設(shè)計一個InterceptorChain 攔截器鏈類

public class InterceptorChain {

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

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

    public void addInterceptor(Interceptor interceptor) {
        interceptorList.add(interceptor);
    }

    /**
     * 返回一個不可修改集合,只能通過addInterceptor方法添加
     * 這樣控制權(quán)就在自己手里
     * @return
     */
    public List<Interceptor> getInterceptorList() {
        return Collections.unmodifiableList(interceptorList);
    }


}

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

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        LogInterceptor logInterceptor = new LogInterceptor();
        InterceptorChain interceptorChain = new InterceptorChain();
        interceptorChain.addInterceptor(transactionInterceptor);
        interceptorChain.addInterceptor(logInterceptor);
        target = (Target) interceptorChain.pluginAll(target);
        target.execute(" HelloWord ");

    }
}

Mybatis Plugin 插件分析

經(jīng)過上面的分析,再去看mybastis plugin 源碼的時候就很輕松了。

mybatis-plugin代碼圖

有沒有覺得似曾相似的感覺呢,沒錯你的感覺是對的,這基本和我們上面的最終實現(xiàn)是一致的,Plugin 相當于我們的TargetProxy。

Mybatis Plugin 介紹及配置使用

MyBatis 允許你在已映射語句執(zhí)行過程中的某一點進行攔截調(diào)用。默認情況下,MyBatis允許使用插件來攔截的方法調(diào)用包括:

1.Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 攔截執(zhí)行器的方法;
2.ParameterHandler (getParameterObject, setParameters) 攔截參數(shù)的處理;
3.ResultSetHandler (handleResultSets, handleOutputParameters) 攔截結(jié)果集的處理;
4.StatementHandler (prepare, parameterize, batch, update, query) 攔截Sql語法構(gòu)建的處理

參考Mybatis 官方的一個例子:

  1. 在全局配置文件mybatis-config.xml 添加

    <plugins>
        <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin>
    </plugins>
    
  2. 寫好攔截類代碼

    @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) {
        }
    }
    
    

    這個攔截器會攔截Executor接口的update方法

源碼簡要分析

首先從配置文件解析開始

public class XMLConfigBuilder extends BaseBuilder {
    //解析配置
  private void parseConfiguration(XNode root) {
    try {
     //省略部分代碼
      pluginElement(root.evalNode("plugins"));
     
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
    
   private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        String interceptor = child.getStringAttribute("interceptor");
        Properties properties = child.getChildrenAsProperties();
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        interceptorInstance.setProperties(properties);
        //調(diào)用InterceptorChain.addInterceptor
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
}

上面的代碼主要是解析配置文件的plugin節(jié)點,根據(jù)配置的interceptor 屬性實例化Interceptor 對象,然后添加到Configuration 對象中的InterceptorChain 屬性中

public class InterceptorChain {


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

  public Object pluginAll(Object target) {
    //循環(huán)調(diào)用每個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);
  }

}

這個就和我們上面實現(xiàn)的是一樣的。定義了攔截器鏈,初始化配置文件的時候就把所有的攔截器添加到攔截器鏈中,下面來看一下什么時候把攔截器插入到需要攔截的接口中

public class Configuration {

    protected final InterceptorChain interceptorChain = new InterceptorChain();
    //創(chuàng)建參數(shù)處理器
  public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    //創(chuàng)建ParameterHandler
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    //插件在這里插入
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  }

  //創(chuàng)建結(jié)果集處理器
  public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    //創(chuàng)建DefaultResultSetHandler
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    //插件在這里插入
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }

  //創(chuàng)建語句處理器
  public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    //創(chuàng)建路由選擇語句處理器
    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);
  }

  //產(chǎn)生執(zhí)行器
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    //這句再做一下保護,囧,防止粗心大意的人將defaultExecutorType設(shè)成null?
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    //然后就是簡單的3個分支,產(chǎn)生3種執(zhí)行器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);
    }
    //此處調(diào)用插件,通過插件可以改變Executor行為
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
}

從代碼可以看出mybatis 在實例化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大接口對象的時候調(diào)用interceptorChain.pluginAll() 方法插入進去的。其實就是循環(huán)執(zhí)行攔截器鏈所有的攔截器的plugin() 方法,mybatis官方推薦的plugin方法是Plugin.wrap() 方法,這個類就是我們上面的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);
    //產(chǎn)生代理,是Interceptor注解的接口的實現(xiàn)類才會產(chǎn)生代理
    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實現(xiàn)類注解的方法才會攔截處理
      if (methods != null && methods.contains(method)) {
        //調(diào)用Interceptor.intercept,也即插入了我們自己的邏輯
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //最后還是執(zhí)行原來邏輯
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
    
    //取得簽名Map,就是獲取Interceptor實現(xiàn)類上面的注解,要攔截的是那個類(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是數(shù)組型,Signature的數(shù)組
    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()]);
  }
}
總結(jié)

Mybatis 攔截器的使用是實現(xiàn)Interceptor接口

public interface Interceptor {

  //攔截
  Object intercept(Invocation invocation) throws Throwable;

  //插入
  Object plugin(Object target);

  //設(shè)置屬性(擴展)
  void setProperties(Properties properties);

}

通過上面的分析可以知道,所有可能被攔截的處理類都會生成一個代理類,如果有N個攔截器,就會有N個代理,層層生成動態(tài)代理是比較耗性能的。而且雖然能指定插件攔截的位置,但這個是在執(zhí)行方法時利用反射動態(tài)判斷的,初始化的時候就是簡單的把攔截器插入到了所有可以攔截的地方。所以盡量不要編寫不必要的攔截器。

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

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

  • MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實這是攔截器功能。那么攔截器攔截MyBati...
    七寸知架構(gòu)閱讀 3,318評論 3 54
  • 《 一生所愛》從前現(xiàn)在過去了再不來紅紅落葉長埋塵土內(nèi)開始終結(jié)總是沒變改天邊的你飄泊白云外苦海翻起愛恨在世間難逃避命...
    莫那一魯?shù)?/span>閱讀 2,467評論 8 8
  • 1.需求背景 設(shè)定訂單表order,要根據(jù)訂單類型統(tǒng)計訂單數(shù)據(jù),大致sql如下: Mybatis無法將以上sql以...
    48892085f47c閱讀 7,382評論 0 2
  • Mybatis插件介紹 為了提高Mybatis的可擴展能力,Mybatis引入的插件機制,允許開發(fā)人員通過責任鏈編...
    dayspring閱讀 1,493評論 0 4
  • 1、超級聯(lián)系人 超聯(lián):,即直接切入具有廣泛傳播能力的中樞,然后通過它實現(xiàn)大規(guī)模聯(lián)系。 就是去了解人們需要什么,然后...
    李一白__閱讀 212評論 0 1

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