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是被攔截的對象,作用是給攔截對象生成一個(gè)代理對象,并返回代理對象;
  Object plugin(Object target);
  //在plugin中配置所需要的參數(shù),方法在初始化的時(shí)候被調(diào)用一次。
  void setProperties(Properties properties);
}
插件的初始化:

插件的初始化是在Mybatis初始化的時(shí)候完成的,代碼在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)建代理的過程,這個(gè)創(chuàng)建代理的過程Mybatis給我們提供一個(gè)工具類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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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

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