天天看點

Mybatis插件原理分析(一)

我們首先介紹一下Mybatis插件相關的幾個類,并對源碼進行了簡單的分析。

Mybatis插件相關的接口或類有:Intercept、InterceptChain、Plugin和Invocation,這幾個接口或類實作了整個Mybatis插件流程。

Interceptor:一個接口,是實作自己功能需要實作的接口

源碼如下:

/**
 * @author Clinton Begin
 */
public interface Interceptor {

  //在此方法中實作自己需要的功能,最後執行invocation.proceed()方法,實際就是調用method.invoke(target, args)方法,調用代理類
  Object intercept(Invocation invocation) throws Throwable;

  //這個方法是将target生成代理類
  Object plugin(Object target);
  //在xml中注冊Intercept是配置一些屬性
  void setProperties(Properties properties);

}      

InterceptorChain:有一個List<Interceptor> interceptors變量,來儲存所有Interceptor的實作類

源碼如下:

/**
 * @author Clinton Begin
 */
public class InterceptorChain {

  //插件攔截器鍊
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  //把target變成代理類,這樣在運作target方法之前需要運作Plugin的invoke方法
  public Object pluginAll(Object target) {
    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);
  }

}      

Invocation:一個比較簡單的類,主要的功能就是根據構造函數類執行代理類

源碼如下:

/**
 * @author Clinton Begin
 */
public class Invocation {

  private Object target;
  private Method method;
  private Object[] args;

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

  public Object getTarget() {
    return target;
  }

  public Method getMethod() {
    return method;
  }

  public Object[] getArgs() {
    return args;
  }
  //其實mybatis的Interceptor最終還是調用的method.invoke方法
  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}      

Plugin:Mybatis插件的核心類,它實作了代理接口InvocationHandler,是一個代理類

/**
 * @author Clinton Begin
 */
//這個類是Mybatis攔截器的核心,大家可以看到該類繼承了InvocationHandler
//又是JDK動态代理機制
public class Plugin implements InvocationHandler {

  //目标對象
  private Object target;
  //攔截器
  private Interceptor interceptor;
  //記錄需要被攔截的類與方法
  private Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  //一個靜态方法,對一個目标對象進行包裝,生成代理類。
  public static Object wrap(Object target, Interceptor interceptor) {
  //首先根據interceptor上面定義的注解 擷取需要攔截的資訊
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
  //如果長度為>0 則傳回代理類 否則不做處理
    if (interfaces.length > 0) {
    //建立JDK動态代理對象
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  //在執行Executor、ParameterHandler、ResultSetHandler和StatementHandler的實作類的方法時會調用這個方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
    //通過method參數定義的類 去signatureMap當中查詢需要攔截的方法集合
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
    //判斷是否是需要攔截的方法,如果需要攔截的話就執行實作的Interceptor的intercept方法,執行完之後還是會執行method.invoke方法,不過是放到interceptor實作類中去實作了
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
    //不攔截 直接通過目标對象調用方法
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
  //根據攔截器接口(Interceptor)實作類上面的注解擷取相關資訊
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
  //擷取注解資訊
    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());      
    }
  //獲得Signature注解資訊
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
  //循環注解資訊
    for (Signature sig : sigs) {
    //根據Signature注解定義的type資訊去signatureMap當中查詢需要攔截方法的集合
      Set<Method> methods = signatureMap.get(sig.type());
    //第一次肯定為null 就建立一個并放入signatureMap
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
    //找到sig.type當中定義的方法 并加入到集合
        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;
  }
  //根據對象類型與signatureMap擷取接口資訊
  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
  //循環type類型的接口資訊 如果該類型存在與signatureMap當中則加入到set當中去
    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()]);
  }

}      
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) {
    return newExecutor(transaction, defaultExecutorType);
  }

  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;
  }