java MyBatis攔截器Inteceptor詳細介紹_java

來源:互聯網
上載者:User

有許多java初學者對於MyBatis攔截器Inteceptor不是很瞭解,在這裡我來為各位整理下篇關於java中MyBatis攔截器Inteceptor詳解,

本文主要分析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);  } } /* 省略代碼... */}

可以看到MyBatis的攔截器設計核心代碼還是比較簡單的,但是足夠靈活。實際使用時注意,不做無意義的代理(Plugin.wrap)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.