MyBatis中plugin原理分析

首先Plugin必須實現Interceptor 常攔截以下類或接口中的方法:

  • Executor
  • ParameterHandler
  • ResultSetHandler
  • StatementHandler
    與Plugin有關的類:pluginInterceptorChain
//自定義一個插件類
@Intercepts({@Signature(type = Executor.class,
        method ="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
public class CustomPlugins implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
     	//最終plugin插件調用的是這個方法
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        System.out.println(String.format("plugin output sql = %s , param=%s", boundSql.getSql(),boundSql.getParameterObject()));
        //放行 該方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        Object obj= Plugin.wrap(o,this);
        return obj;
    }

    @Override
    public void setProperties(Properties properties) {
        //常用於將配置中的參數賦值給類的實例變量
        String value = (String) properties.get("name");
        System.out.println(value);
    }
}
//InterceptorChain類
public class InterceptorChain {

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

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      //這裏的intecetor是Plugin 也即是自定義插件中plugin方法 
      //這裏的target是Executor、ParameterHandler、ResultSetHandler、StatementHandler接口的實現類 具體是什麼 要看@Interceptors中攔截的接口
      //這裏的target是通過for循環不斷賦值的,也就是說如果有多個攔截器,那麼如果我用P表示代理,生成第       //一次代理爲P(target),生成第二次代理爲P(P(target)),生成第三次代理爲P(P(P(target))),不斷      //嵌套下去,這就得到一個重要的結論:<plugins>...</plugins>中後定義的<plugin>實際其攔截器方法     //先被執行,因爲根據這段代碼來看,後定義的<plugin>代理實際後生成,包裝了先生成的代理,自然其代理方     //法也先執行.也即是interceptor的執行順序 後定義先執行
      //這裏的plugin方法實際上是調用對應攔截器類的重載方法
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
      //添加攔截器至集合
    interceptors.add(interceptor);
  }
 //	列舉所有的攔截器類 
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}
//Plugin類
public static Object wrap(Object target, Interceptor interceptor) {
    //獲取攔截器的簽名信息,具體代碼如下
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //如果數組長度大於0 也就是表示type有父接口 可以根據其接口生成代理對象
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    //否則 返回target對象本身
    return target;
  }

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //method#getDeclaringClass() 獲取method對應的class類 
        //以CustomPlugin爲例,此時method爲query 得到的的declaringClass爲Executor
        //此時簽名Map中可以得到key爲Executor的value
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
          //這裏調用攔截器中的intercept方法 攔截器對應具體的實現 如此時是CustomPlugin
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

//getSignatureMap方法

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    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());      
    }
      //以CustomPlugins爲例@Intercepts({@Signature(type = Executor.class,
      //method ="query",
    //args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
	//type=Executor.class,method=query args=...
    Signature[] sigs = interceptsAnnotation.value();
      //如果存在以type爲key的map 則獲取其攔截的方法 否則執行map的put方法 爲key賦值
    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 {
          //利用反射 獲取Executor中方法爲query,參數爲sig.args的方法
        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);
      }
    }
    //返回簽名map
    return signatureMap;
  }
//getInterfaces
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    while (type != null) {
        //如此時type爲Executor的具體實例 CachingExecutor
        //type.getInterfaces 得到的是Executor
        //剛好Executor.class 爲map的key
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
        //向上查詢 查詢其父類
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章