Mybatis plugs (6)2018-08-21

?Mybatis為我們提供插件技術(shù),在我們sql執(zhí)行流程過程中創(chuàng)建SqlSession的四大對象進(jìn)行自定義代碼處理的分裝其馏,實(shí)現(xiàn)一些特殊的需求夭苗。

接口定義:

我們在mybatis中使用插件都要實(shí)現(xiàn)Interceptor接口:

public interface Interceptor {
  //它將攔截對象的原有方法缀遍,因此他是插件的核心方法筷弦,可以通過invocation參數(shù)反射調(diào)用原來的方法
  Object intercept(Invocation invocation) throws Throwable;
  //target是被攔截的對象溅潜,作用是給攔截對象生成一個代理對象术唬,并返回代理對象;
  Object plugin(Object target);
  //在plugin中配置所需要的參數(shù)滚澜,方法在初始化的時候被調(diào)用一次粗仓。
  void setProperties(Properties properties);
}
插件的初始化:

插件的初始化是在Mybatis初始化的時候完成的,代碼在XMLConfigBuilder中的pluginElement(XNode parent):

 public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      //執(zhí)行
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        reader.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
//執(zhí)行
 public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
  //執(zhí)行
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }
//執(zhí)行
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      //解析插件
      pluginElement(root.evalNode("plugins"));
      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).newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
插件的使用:

從Sql執(zhí)行流程中我們很容易明白插件的調(diào)用位置和代碼:

executor = interceptorChain.pluginAll(executor);

public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
//調(diào)用plugs鏈
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      //可以根據(jù)Interceptor接口的定義返回的是代理對象
      target = interceptor.plugin(target);
    }
    return target;
  }
  //添加plugs鏈
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
 //獲取plugs鏈
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }
}

這里的重點(diǎn)還是interceptor.plugin(target)創(chuàng)建代理的過程设捐,這個創(chuàng)建代理的過程Mybatis給我們提供一個工具類org.apache.ibatis.plugin.Plugin可以為我們提供非常便利的創(chuàng)建代理對象:

public class Plugin implements InvocationHandler {

  private Object target;
  private Interceptor interceptor;
  private Map<Class<?>, Set<Method>> signatureMap;
  //構(gòu)造方法
  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;//目標(biāo)對象
    this.interceptor = interceptor;//目標(biāo)對象實(shí)現(xiàn)的接口
    this.signatureMap = signatureMap;//Signature的注解信息
  }
  //靜態(tài)方法獲取代理
  public static Object wrap(Object target, Interceptor interceptor) {
    //解析plug實(shí)現(xiàn)類中的注解配置
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    //獲取目標(biāo)對象的Class對象
    Class<?> type = target.getClass();
    //從signatureMap獲取匹配的interfaces對象
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      //創(chuàng)建代理
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
//InvocationHandler 額外功能方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //signatureMap中獲取匹配的方法
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        //調(diào)用插件interceptor中的攔截方法
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //直接待用目標(biāo)方法
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
  //解析plug實(shí)現(xiàn)類中的注解配置
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    //獲取Interceptes注解
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // plug實(shí)現(xiàn)類不存在Intercepts注解 則拋出異常
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
     //獲取配置的Singature數(shù)組
    Signature[] sigs = interceptsAnnotation.value();
    //容器用于保持目標(biāo)對象和注解匹配成功信息
    //key :interceptor中要攔截的目標(biāo)類(sqlSession的四大對象)
    //value:要攔截的方法
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    //便利注解中配置的Signature數(shù)組
    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()]);
  }

}

插件工具類注解案例:

//Intercepts 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
  Signature[] value();
}
//Signature注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
  Class<?> type();

  String method();

  Class<?>[] args();
}

//案例
@Intercepts({
@Signature(type=Executor.class,
method= "query", 
args = { MappedStatement.class, Object.class,RowBounds.class, 
ResultHandler.class }),
@Signature(type = Executor.class, 
method = "update", 
args = { MappedStatement.class, Object.class }) })
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末潦牛,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子挡育,更是在濱河造成了極大的恐慌,老刑警劉巖朴爬,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件即寒,死亡現(xiàn)場離奇詭異,居然都是意外死亡召噩,警方通過查閱死者的電腦和手機(jī)母赵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來具滴,“玉大人凹嘲,你說我怎么就攤上這事」乖希” “怎么了周蹭?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疲恢。 經(jīng)常有香客問我凶朗,道長,這世上最難降的妖魔是什么显拳? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任棚愤,我火速辦了婚禮,結(jié)果婚禮上杂数,老公的妹妹穿的比我還像新娘宛畦。我一直安慰自己,他們只是感情好揍移,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布次和。 她就那樣靜靜地躺著,像睡著了一般那伐。 火紅的嫁衣襯著肌膚如雪斯够。 梳的紋絲不亂的頭發(fā)上囚玫,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天,我揣著相機(jī)與錄音读规,去河邊找鬼抓督。 笑死,一個胖子當(dāng)著我的面吹牛束亏,可吹牛的內(nèi)容都是我干的铃在。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼碍遍,長吁一口氣:“原來是場噩夢啊……” “哼定铜!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起怕敬,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤揣炕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后东跪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體畸陡,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年虽填,在試婚紗的時候發(fā)現(xiàn)自己被綠了丁恭。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡斋日,死狀恐怖牲览,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情恶守,我是刑警寧澤第献,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站兔港,受9級特大地震影響痊硕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜押框,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一岔绸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧橡伞,春花似錦盒揉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至挂脑,卻和暖如春藕漱,著一層夾襖步出監(jiān)牢的瞬間欲侮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工肋联, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留威蕉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓橄仍,卻偏偏與公主長得像韧涨,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子侮繁,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評論 2 355

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

  • 八大行星 太陽~水星~金星~地球~火星~木星~土星~天王星~海王星
    娜安熙閱讀 179評論 0 0
  • Tags: 點(diǎn)子 董哥哥發(fā)微信過來說房子要漲價虑粥,我一驚,這老頭宪哩,太賤了娩贷。還好老頭是要漲兩百塊,這個幅度也漲了8個多...
    哈慈開閱讀 91評論 0 0
  • 孩子,是父母的理念不對罗岖,在你困難沒能疏導(dǎo)好你的心情,在你的小時候承壓環(huán)境創(chuàng)造的太少了腹躁,前段遇到困難我們沒能去正確解...
    陽光_722f閱讀 366評論 0 1