詳解Mybatis攔截器(從使用到源碼)


詳解Mybatis攔截器(從使用到源碼)

MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實這是攔截器功能。

本文從配置到源碼進行分析.

一、攔截器介紹

MyBatis 允許你在已映射語句執行過程中的某一點進行攔截調用。默認情況下,MyBatis 允許使用插件來攔截的方法調用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

概括一下,分別是攔截執行器、參數控制器、結果控制器、SQL語句構建控制器,對執行流程進行更改.對應四個對象:

二、攔截器圖示

三、攔截器使用

1、測試類

    @Test
    public  void testQueryByNo() throws IOException {
        Reader reader =
                Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory sessionFactory
                = new SqlSessionFactoryBuilder().build(reader);              
        SqlSession session = sessionFactory.openSession();
        //傳入StudentMapper接口,返回該接口的mapper代理對象studentMapper
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);//接口
        //通過mapper代理對象studentMapper,來調用IStudentMapper接口中的方法
        Student student = studentMapper.queryStudentByNo(1);
        System.out.println(student);
        session.close();
    }

2、實現接口

自定義類實現Interceptor接口

public class MyInterceptor implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        //放行方法
        Object proceed = invocation.proceed();
        return proceed;
    }
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }
    public void setProperties(Properties properties) {
    }
}
類中方法解釋:

intercept :起攔截作用,在此定義一些功能

plugin :將需要增強的方法以及攔截器中增強的部分整合再返回,這個方法會執行四次,對四個處理器都會增

​ 強,第一次執行是在sessionFactory.openSession()之后,由源碼可以知道四個默認攔截器是:

		>		>	>CachingExecutor
		>		>	>
		>		>	>DefaultParameterHandler
		>		>	>
		>		>	>DefaultResultSetHandler
		>		>	>
		>		>	>RoutingStatementHandler

setProperties :設置變量屬性,這個方法在SqlSessionFactoryBuilder().build(reader)之后執行

3、添加注解

在上面的實現類上添加注解

@Intercepts({
        @Signature(
                type = StatementHandler.class,
                method = "query",
                args = {Statement.class, ResultHandler.class}
        )

})

signature參數解釋:

​ type : 這兒主要是攔截對象的類型,是前面攔截器介紹中的四種之一,或多種(源碼中type返回值是數組)
method : 方法只能是一個值,
​ args: 值是前面介紹的四種攔截器括號中的內容,可以有多個.

4、配置文件

修改mybatis-config.xml文件

位置:typeAliases之后,environments之前(如果不記得,可以故意輸錯,然后idea會提示)

    <plugins>
       <plugin interceptor="com.courage.mybatis.my.interceptors.MyInterceptor">
           <property name="name" value="zs"/>
           <property name="age" value="23"/>
       </plugin>
    </plugins>

四、多個攔截器執行順序

如果有多個攔截器,攔截順序會按照mybatis-config.xml中plugins標簽里面攔截器先后順序,但是調用執行的順序相反

五、攔截器攔截后進行修改

    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(target);
        Object value = metaObject.getValue("parameterHandler.parameterObject");
        metaObject.setValue("parameterHandler.parameterObject",2);
        Object proceed = invocation.proceed();
        return proceed;
    }

要點:

metaObject.getValue()方法是參數值,可以通過打印上一步的target,獲取對象(類)源碼,查看類中包含的value

在本文分析的RoutingStatementHandler中,有兩個可以get的值(get表示有這個屬性),而 metaObject.setValue("parameterHandler.parameterObject",2);中的parameterHandler就是默認的DefaultParameterHandler,可以通過打印攔截器里面的plugin方法里面的wrap得知:

org.apache.ibatis.executor.CachingExecutor@bcef303
org.apache.ibatis.scripting.defaults.DefaultParameterHandler@2f1de2d6
org.apache.ibatis.executor.resultset.DefaultResultSetHandler@289710d9
org.apache.ibatis.executor.statement.RoutingStatementHandler@5143c662

對得到的參數對象重新進行賦值為2(原來為1)查詢,結果:

學號:2	姓名:lixiaosi	年齡:30	年級:middle

六、源碼分析

首先從源頭->配置文件開始分析:

1、pluginElement方法

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

2、InterceptorChain類

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

}

3、為何攔截器會攔截幾個處理器?

現在我們理解了攔截器配置的解析以及攔截器的歸屬,現在我們回過頭看下為何攔截器會攔截這些方法(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即可,可使用反射實現。

4、Plugin類的使用

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自身提供的動態代理類。我們解剖一下這個方法調用的其他方法:

5、getSignatureMap方法

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方法對應不上,那么將會拋出異常。

6、getAllInterfaces

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方法也就是調用原先方法(不走代理)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM