MyBatis攔截器原理介紹

系列

Mybatis攔截器介紹

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

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



mybatis執(zhí)行流程

  • mybatis在執(zhí)行過程中按照Executor => StatementHandler => ParameterHandler => ResultSetHandler也颤。
  • Executor在執(zhí)行過程中會(huì)創(chuàng)建StatementHandler,在創(chuàng)建StatementHandler過程中會(huì)創(chuàng)建 ParameterHandler和ResultSetHandler葫隙。

Mybatis攔截器的使用

---------定義攔截器
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "createCacheKey", args = {MappedStatement.class, Object.class, RowBounds.class, BoundSql.class})
})
public class ExamplePlugin implements Interceptor {
  private Properties properties = new Properties();
  public Object intercept(Invocation invocation) throws Throwable {
    // implement pre processing if need

    Object returnObject = invocation.proceed();

    // implement post processing if need
    return returnObject;
  }

  public void setProperties(Properties properties) {
    this.properties = properties;
  }
}

---------mybatis全局xml配置
<plugins>
    <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin>
</plugins>

自定義一個(gè)mybatis的攔截器步驟包含:

  • 定義實(shí)現(xiàn)org.apache.ibatis.plugin.Interceptor接口的類娄帖。
  • 在mybatis的全局配置xml中配置插件plugin。
public interface Executor {

  ResultHandler NO_RESULT_HANDLER = null;
  int update(MappedStatement ms, Object parameter) throws SQLException;
  <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;
  <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;
  <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException;
  List<BatchResult> flushStatements() throws SQLException;
  void commit(boolean required) throws SQLException;
  void rollback(boolean required) throws SQLException;
  CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);
  boolean isCached(MappedStatement ms, CacheKey key);
  void clearLocalCache();
  void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType);
  Transaction getTransaction();
  void close(boolean forceRollback);
  boolean isClosed();
  void setExecutorWrapper(Executor executor);
}


public interface ParameterHandler {

  Object getParameterObject();
  void setParameters(PreparedStatement ps) throws SQLException;
}


public interface ResultSetHandler {

  <E> List<E> handleResultSets(Statement stmt) throws SQLException;
  <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException;
  void handleOutputParameters(CallableStatement cs) throws SQLException;
}


public interface StatementHandler {

  Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException;
  void parameterize(Statement statement) throws SQLException;
  void batch(Statement statement) throws SQLException;
  int update(Statement statement) hrows SQLException;
  <E> List<E> query(Statement statement, ResultHandler resultHandler) hrows SQLException;
  <E> Cursor<E> queryCursor(Statement statement) hrows SQLException;
  BoundSql getBoundSql();
  ParameterHandler getParameterHandler();
}

攔截點(diǎn)說明:

  • 不同攔截點(diǎn)能夠支持?jǐn)r截的方法麦撵。
  • 攔截方法的type上遥、method搏屑、args等都取自上述方法。

Mybatis攔截器原理

攔截器的原理核心的內(nèi)容在于攔截器配置解析粉楚、攔截器的職責(zé)鏈構(gòu)造辣恋、攔截器的執(zhí)行,串聯(lián)上述功能后就能傳統(tǒng)整體的流程模软。

攔截器解析

private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));  // 解析插件相關(guān)的參數(shù)
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } 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).getDeclaredConstructor().newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance); // 保存攔截器
      }
    }
  }


public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<>(); // 全局變量保存所有的攔截器

  // 織入攔截器
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  // 負(fù)責(zé)保存所有的攔截器
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }

  // 獲取所有攔截器
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

攔截器解析說明:

  • 負(fù)責(zé)解析XML配置文件解析所有的攔截器對(duì)象保存到攔截器鏈InterceptorChain 伟骨。
  • InterceptorChain通過pluginAll植入攔截器。

攔截器織入

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    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) {
    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, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    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);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }

    // 插入攔截器
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

攔截器織入說明:

  • 針對(duì)ParameterHandler 燃异、ResultSetHandler 携狭、StatementHandler 、Executor 的攔截器的植入都是通過interceptorChain.pluginAll來實(shí)現(xiàn)回俐。
public class InterceptorChain {

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

  public Object pluginAll(Object target) {
    // 遍歷所有的攔截器負(fù)責(zé)進(jìn)行植入
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }
}

public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;
  // 通過wrap織入單個(gè)攔截器
  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  default void setProperties(Properties properties) {
    // NOP
  }

}

public class Plugin implements InvocationHandler {

  public static Object wrap(Object target, Interceptor interceptor) {
    // 解析攔截器的注解獲取攔截的攔截點(diǎn)和對(duì)應(yīng)的攔截方法
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();

    // 獲取被攔截對(duì)應(yīng)的信息構(gòu)建JDK的動(dòng)態(tài)代理
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      // 針對(duì)注解指定的interface進(jìn)行攔截
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
}

攔截器織入說明:

  • 攔截器織入依賴于JDK自帶的Proxy.newProxyInstance動(dòng)態(tài)代理來實(shí)現(xiàn)逛腿。
  • 返回的對(duì)象是個(gè)Plugin對(duì)象的動(dòng)態(tài)代理。
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    // 1仅颇、獲取所有攔截的Intercepts注解
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
    // 2单默、獲取注解的內(nèi)容
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    // 3、遍歷注解按照type + method維度進(jìn)行構(gòu)建
    for (Signature sig : sigs) {
      Set<Method> methods = MapUtil.computeIfAbsent(signatureMap, sig.type(), k -> new HashSet<>());
      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<>();
    while (type != null) {
      // 獲取攔截點(diǎn)對(duì)應(yīng)的Interfaces并且在攔截點(diǎn)注解配置的的interface用以構(gòu)建動(dòng)態(tài)代理
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[0]);
  }

攔截器織入說明:

  • 通過解析注解@Intercepts注解@Signature來構(gòu)建class + method兩個(gè)維度的map對(duì)象灵莲。
  • 以@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class)為例,會(huì)構(gòu)建key為ParameterHandler殴俱,value為setParameters的map

攔截器執(zhí)行

public class Plugin implements InvocationHandler {

  private final Object target;
  private final Interceptor interceptor;
  private final Map<Class<?>, Set<Method>> signatureMap;

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 判斷是否是被攔截的方法政冻,如果是就通過攔截器進(jìn)行處理
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        // 由攔截器interceptor負(fù)責(zé)處理
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
}

JDK動(dòng)態(tài)代理


public class Main {
    public static void main(String[] args) throws Exception {
        
        final Dog dog = new Dog();

        IDog proxy = (IDog)Proxy.newProxyInstance(Dog.class.getClassLoader(), Dog.class.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                return method.invoke(dog, args);
            }
        });

        proxy.eat();

        Thread.sleep(100000);
    }
}


-------------------------對(duì)應(yīng)生成的動(dòng)態(tài)代碼

package com.sun.proxy;

import com.sunboy.IDog;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements IDog {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public $Proxy0(InvocationHandler invocationHandler) {
        super(invocationHandler);
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.sunboy.IDog").getMethod("eat", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            return;
        }
        catch (NoSuchMethodException noSuchMethodException) {
            throw new NoSuchMethodError(noSuchMethodException.getMessage());
        }
        catch (ClassNotFoundException classNotFoundException) {
            throw new NoClassDefFoundError(classNotFoundException.getMessage());
        }
    }

    public final boolean equals(Object object) {
        try {
            return (Boolean)this.h.invoke(this, m1, new Object[]{object});
        }
        catch (Error | RuntimeException throwable) {
            throw throwable;
        }
        catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final String toString() {
        try {
            return (String)this.h.invoke(this, m2, null);
        }
        catch (Error | RuntimeException throwable) {
            throw throwable;
        }
        catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int hashCode() {
        try {
            return (Integer)this.h.invoke(this, m0, null);
        }
        catch (Error | RuntimeException throwable) {
            throw throwable;
        }
        catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final void eat() {
        try {
            this.h.invoke(this, m3, null);
            return;
        }
        catch (Error | RuntimeException throwable) {
            throw throwable;
        }
        catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }
}
  • JDK動(dòng)態(tài)代理生成的代理類如$Proxy0枚抵,通過arthas去反編譯類。
  • JDK動(dòng)態(tài)代理通過反射獲取Method對(duì)象用以后續(xù)的執(zhí)行明场。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末汽摹,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子苦锨,更是在濱河造成了極大的恐慌逼泣,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,839評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件舟舒,死亡現(xiàn)場(chǎng)離奇詭異拉庶,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)秃励,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門氏仗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人夺鲜,你說我怎么就攤上這事皆尔。” “怎么了币励?”我有些...
    開封第一講書人閱讀 153,116評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵慷蠕,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我食呻,道長(zhǎng)流炕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,371評(píng)論 1 279
  • 正文 為了忘掉前任搁进,我火速辦了婚禮浪感,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘饼问。我一直安慰自己影兽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,384評(píng)論 5 374
  • 文/花漫 我一把揭開白布莱革。 她就那樣靜靜地躺著峻堰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪盅视。 梳的紋絲不亂的頭發(fā)上捐名,一...
    開封第一講書人閱讀 49,111評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音闹击,去河邊找鬼镶蹋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的贺归。 我是一名探鬼主播淆两,決...
    沈念sama閱讀 38,416評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼拂酣!你這毒婦竟也來了秋冰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,053評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤婶熬,失蹤者是張志新(化名)和其女友劉穎剑勾,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體赵颅,經(jīng)...
    沈念sama閱讀 43,558評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡虽另,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,007評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了性含。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片洲赵。...
    茶點(diǎn)故事閱讀 38,117評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖商蕴,靈堂內(nèi)的尸體忽然破棺而出叠萍,到底是詐尸還是另有隱情,我是刑警寧澤绪商,帶...
    沈念sama閱讀 33,756評(píng)論 4 324
  • 正文 年R本政府宣布苛谷,位于F島的核電站,受9級(jí)特大地震影響格郁,放射性物質(zhì)發(fā)生泄漏腹殿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,324評(píng)論 3 307
  • 文/蒙蒙 一例书、第九天 我趴在偏房一處隱蔽的房頂上張望锣尉。 院中可真熱鬧,春花似錦决采、人聲如沸自沧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,315評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拇厢。三九已至,卻和暖如春晒喷,著一層夾襖步出監(jiān)牢的瞬間孝偎,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,539評(píng)論 1 262
  • 我被黑心中介騙來泰國(guó)打工凉敲, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留衣盾,地道東北人寺旺。 一個(gè)月前我還...
    沈念sama閱讀 45,578評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像势决,于是被迫代替她去往敵國(guó)和親迅涮。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,877評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 一徽龟、MyBatis攔截器介紹 MyBatis提供了一種插件(plugin)的功能,雖然叫做插件唉地,但其實(shí)這是攔截器功...
    Lemonrel閱讀 279評(píng)論 0 0
  • 原文作者:Format原文地址:原文鏈接摘抄申明:我們不占有不侵權(quán)据悔,我們只是好文的搬運(yùn)工!轉(zhuǎn)發(fā)請(qǐng)帶上原文申明耘沼。 M...
    Hey_Shaw閱讀 874評(píng)論 0 15
  • 概要:1介紹及配置极颓、2源碼分析、3為何攔截這些方法 4注解 和 Plugin類使用 總結(jié):1)plugin()構(gòu)...
    hedgehog1112閱讀 972評(píng)論 0 0
  • https://www.cnblogs.com/fangjian0423/p/mybatis-intercepto...
    小陳阿飛閱讀 533評(píng)論 0 4
  • Mybatis攔截器 MyBatis 允許你在已映射語句執(zhí)行過程中的某一點(diǎn)進(jìn)行攔截調(diào)用群嗤。默認(rèn)情況下菠隆,MyBatis...
    這個(gè)ID狠溫柔閱讀 378評(píng)論 0 2