天天看點

MyBatis攔截器Inteceptor

轉載自JavaTalk – zhouhaocheng.com

MyBatis的插件機制,實際就是Java動态代理實作的責任鍊模式實作。

根據官方文檔。Mybatis隻允許攔截以下方法,這個決定寫攔截器注解簽名參數。

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

攔截處理的源碼如下,其中interceptorChain.pluginAll(..)即為織入自定義攔截器:

/* org.apache.ibatis.session.Configuration類中方法 */
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
   ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
   /* 攔截ParameterHandler*/
   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 = (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 = (StatementHandler) interceptorChain.pluginAll(statementHandler);
   return statementHandler;
}

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

實作一個自定義攔截器隻需實作Interceptor接口即可,大緻代碼如下:

/* 注解表明要攔截哪個接口的方法及其參數 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class YourInterceptor implements Interceptor{

  public Object intercept(Invocation invocation) throws Throwable{
    doSomeThing();
    /* 注:此處實際上使用Invocation.proceed()方法完成interceptorChain鍊的周遊調用(即執行所有注冊的Interceptor的intercept方法),到最終被代理對象的原始方法調用 */
    return invocation.proceed();
  }

   /*生成成對目标target的代理,而@Intercepts的注解是在Plugin.wrap中用到*/
  @Override
  public Object plugin(Object target){
     /* 當目标類是StatementHandler類型時,才包裝目标類,不做無意義的代理 */
    return (target instanceof StatementHandler)?Plugin.wrap(target, this):target;
  }

   /*用于設定自定義的攔截器配置參數*/
  @Override
  public void setProperties(Properties properties){
  }
}      

其中,攔截調用的代碼均在Plugin.wrap中:

/* org.apache.ibatis.plugin.Plugin類 */
public class Plugin implements InvocationHandler {

  /* 省略代碼... */

  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);
    if (interfaces.length > 0) {
      /* 使用jdk動态代理 */
      return Proxy.newProxyInstance(type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  /* 攔截目标類的所有方法的執行都會變為在此執行 */
  @Override
  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);
    }
  }

  /* 省略代碼... */

}      

繼續閱讀