mybatis拦截器的注解说明

来源:互联网 发布:landsat的波段数据 编辑:程序博客网 时间:2024/06/09 22:08

@Intercepts( @Signature(type = Executor.class,method = "query", 

args = {MappedStatement.class, Object.class, RowBounds.class,ResultHandler.class 

 ) })

type:表示拦截的类,这里是Executor的实现类

method:表示拦截的方法,这里是拦截Executor的query方法

args:表示方法参数

List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;

封装Interceptor对象(org.apache.ibatis.plugin.Plugin)

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


如下是@Signature的解析代码(org.apache.ibatis.plugin.Plugin)

private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Signature[] sigs = interceptor.getClass().getAnnotation(Intercepts.class).value();//获取@Signature对象数组

//[ @org.apache.ibatis.plugin.Signature(type=interface org.apache.ibatis.executor.Executor, method=query, args=[class org.apache.ibatis.mapping.MappedStatement, class Java.lang.Object, class org.apache.ibatis.session.RowBounds, interface org.apache.ibatis.session.ResultHandler]) ]

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

Plugin类负责生成代理,调用具体的拦截器实现类

原创粉丝点击