mybatis拦截器的注解说明

@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类负责生成代理,调用具体的拦截器实现类

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值