1. 程式人生 > >【本人禿頂程式設計師】講解MyBatis攔截器原理探究

【本人禿頂程式設計師】講解MyBatis攔截器原理探究

←←←←←←←←←←←← 我都禿頂了,還不點關注!

MyBatis攔截器介紹

MyBatis提供了一種外掛(plugin)的功能,雖然叫做外掛,但其實這是攔截器功能。那麼攔截器攔截MyBatis中的哪些內容呢?

我們進入官網看一看:

MyBatis 允許你在已對映語句執行過程中的某一點進行攔截呼叫。預設情況下,MyBatis 允許使用外掛來攔截的方法呼叫包括:
Executor (update, query, flushStatements, commit, rollback,
getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)

我們看到了可以攔截Executor介面的部分方法,比如update,query,commit,rollback等方法,還有其他介面的一些方法等。

總體概括為:

  • 攔截執行器的方法
  • 攔截引數的處理
  • 攔截結果集的處理
  • 攔截Sql語法構建的處理

攔截器的使用

攔截器介紹及配置

首先我們看下MyBatis攔截器的介面定義:

public interface Interceptor {
  Object intercept(Invocation invocation) throws Throwable;
  Object plugin(Object target);
  void setProperties(Properties properties);
}

比較簡單,只有3個方法。 MyBatis預設沒有一個攔截器介面的實現類,開發者們可以實現符合自己需求的攔截器。

下面的MyBatis官網的一個攔截器例項:

@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
  public Object intercept(Invocation invocation) throws Throwable {
    return invocation.proceed();
  }
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  public void setProperties(Properties properties) {
  }
}

全域性xml配置:

<plugins>
    <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin>
</plugins>

這個攔截器攔截Executor介面的update方法(其實也就是SqlSession的新增,刪除,修改操作),所有執行executor的update方法都會被該攔截器攔截到。

原始碼分析

下面我們分析一下這段程式碼背後的原始碼。

首先從源頭->配置檔案開始分析:

XMLConfigBuilder解析MyBatis全域性配置檔案的pluginElement私有方法:

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

具體的解析程式碼其實比較簡單,就不貼了,主要就是通過反射例項化plugin節點中的interceptor屬性表示的類。然後呼叫全域性配置類Configuration的addInterceptor方法。

public void addInterceptor(Interceptor interceptor) {
       interceptorChain.addInterceptor(interceptor);
     }

這個interceptorChain是Configuration的內部屬性,型別為InterceptorChain,也就是一個攔截器鏈,我們來看下它的定義:

public class InterceptorChain {
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
  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);
  }
}

現在我們理解了攔截器配置的解析以及攔截器的歸屬,現在我們回過頭看下為何攔截器會攔截這些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler的部分方法):

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, boolean autoCommit) {
    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, autoCommit);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

以上4個方法都是Configuration的方法。這些方法在MyBatis的一個操作(新增,刪除,修改,查詢)中都會被執行到,執行的先後順序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的建立是在建立StatementHandler[3個可用的實現類CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的時候,其建構函式呼叫的[這3個實現類的建構函式其實都呼叫了父類BaseStatementHandler的建構函式])。

這4個方法例項化了對應的物件之後,都會呼叫interceptorChain的pluginAll方法,InterceptorChain的pluginAll剛才已經介紹過了,就是遍歷所有的攔截器,然後呼叫各個攔截器的plugin方法。注意:攔截器的plugin方法的返回值會直接被賦值給原先的物件

由於可以攔截StatementHandler,這個介面主要處理sql語法的構建,因此比如分頁的功能,可以用攔截器實現,只需要在攔截器的plugin方法中處理StatementHandler介面實現類中的sql即可,可使用反射實現。

MyBatis還提供了 @Intercepts和 @Signature關於攔截器的註解。官網的例子就是使用了這2個註解,還包括了Plugin類的使用:

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

下面我們就分析這3個 “新組合” 的原始碼,首先先看Plugin類的wrap方法:

public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
}

Plugin類實現了InvocationHandler介面,很明顯,我們看到這裡返回了一個JDK自身提供的動態代理類。我們解剖一下這個方法呼叫的其他方法:

getSignatureMap方法:

private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    if (interceptsAnnotation == null) { // issue #251
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    Signature[] sigs = interceptsAnnotation.value();
    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 {
        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;
}

getSignatureMap方法解釋:首先會拿到攔截器這個類的 @Interceptors註解,然後拿到這個註解的屬性 @Signature註解集合,然後遍歷這個集合,遍歷的時候拿出 @Signature註解的type屬性(Class型別),然後根據這個type得到帶有method屬性和args屬性的Method。由於 @Interceptors註解的 @Signature屬性是一個屬性,所以最終會返回一個以type為key,value為Set的Map。

@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class})})

比如這個 @Interceptors註解會返回一個key為Executor,value為集合(這個集合只有一個元素,也就是Method例項,這個Method例項就是Executor介面的update方法,且這個方法帶有MappedStatement和Object型別的引數)。這個Method例項是根據 @Signature的method和args屬性得到的。如果args引數跟type型別的method方法對應不上,那麼將會丟擲異常。

getAllInterfaces方法:

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()]);
}

getAllInterfaces方法解釋:根據目標例項target(這個target就是之前所說的MyBatis攔截器可以攔截的類,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父類們,返回signatureMap中含有target實現的介面陣列。

所以Plugin這個類的作用就是根據 @Interceptors註解,得到這個註解的屬性 @Signature陣列,然後根據每個 @Signature註解的type,method,args屬性使用反射找到對應的Method。最終根據呼叫的target物件實現的介面決定是否返回一個代理物件替代原先的target物件。

比如MyBatis官網的例子,當Configuration呼叫newExecutor方法的時候,由於Executor介面的update(MappedStatement ms, Object parameter)方法被攔截器被截獲。因此最終返回的是一個代理類Plugin,而不是Executor。這樣呼叫方法的時候,如果是個代理類,那麼會執行:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      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介面的interceptor方法。

這個Invocation類如下:

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

  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}

它的proceed方法也就是呼叫原先方法(不走代理)。

總結

MyBatis攔截器介面提供的3個方法中,plugin方法用於某些處理器(Handler)的構建過程。interceptor方法用於處理代理類的執行。setProperties方法用於攔截器屬性的設定。

其實MyBatis官網提供的使用 @Interceptors和 @Signature註解以及Plugin類這樣處理攔截器的方法,我們不一定要直接這樣使用。我們也可以拋棄這3個類,直接在plugin方法內部根據target例項的型別做相應的操作。

總體來說MyBatis攔截器還是很簡單的,攔截器本身不需要太多的知識點,但是學習攔截器需要對MyBatis中的各個介面很熟悉,因為攔截器涉及到了各個介面的知識點。

禿頂程式設計師的不易,看到這裡,點個關注吧!