Mybatis拦截器介绍及分页插件

来源:互联网 发布:配电网优化运行 编辑:程序博客网 时间:2024/05/01 20:34

 拦截器的一个作用就是我们可以拦截某些方法的调用,我们可以选择在这些被拦截的方法执行前后加上某些逻辑,也可以在执行这些被拦截的方法时执行自己的逻辑而不再执行被拦截的方法。Mybatis拦截器设计的一个初衷就是为了供用户在某些时候可以实现自己的逻辑而不必去动Mybatis固有的逻辑。打个比方,对于Executor,Mybatis中有几种实现:BatchExecutor、ReuseExecutor、SimpleExecutor和CachingExecutor。这个时候如果你觉得这几种实现对于Executor接口的query方法都不能满足你的要求,那怎么办呢?是要去改源码吗?当然不。我们可以建立一个Mybatis拦截器用于拦截Executor接口的query方法,在拦截之后实现自己的query方法逻辑,之后可以选择是否继续执行原来的query方法。

     Interceptor接口

       对于拦截器Mybatis为我们提供了一个Interceptor接口,通过实现该接口就可以定义我们自己的拦截器。我们先来看一下这个接口的定义:

    package org.apache.ibatis.plugin;  
       
    import java.util.Properties;  
       
    public interface Interceptor {  
       
      Object intercept(Invocation invocation) throws Throwable;  
       
      Object plugin(Object target);  
       
      void setProperties(Properties properties);  
       
    }  

 

       我们可以看到在该接口中一共定义有三个方法,intercept、plugin和setProperties。plugin方法是拦截器用于封装目标对象的,通过该方法我们可以返回目标对象本身,也可以返回一个它的代理。当返回的是代理的时候我们可以对其中的方法进行拦截来调用intercept方法,当然也可以调用其他方法,这点将在后文讲解。setProperties方法是用于在Mybatis配置文件中指定一些属性的。

       定义自己的Interceptor最重要的是要实现plugin方法和intercept方法,在plugin方法中我们可以决定是否要进行拦截进而决定要返回一个什么样的目标对象。而intercept方法就是要进行拦截的时候要执行的方法。

       对于plugin方法而言,其实Mybatis已经为我们提供了一个实现。Mybatis中有一个叫做Plugin的类,里面有一个静态方法wrap(Object target,Interceptor interceptor),通过该方法可以决定要返回的对象是目标对象还是对应的代理。这里我们先来看一下Plugin的源码:

    package org.apache.ibatis.plugin;  
       
    import java.lang.reflect.InvocationHandler;  
    import java.lang.reflect.Method;  
    import java.lang.reflect.Proxy;  
    import java.util.HashMap;  
    import java.util.HashSet;  
    import java.util.Map;  
    import java.util.Set;  
       
    import org.apache.ibatis.reflection.ExceptionUtil;  
       
    public class Plugin implements InvocationHandler {  
       
      private Object target;  
      private Interceptor interceptor;  
      private Map<Class<?>, Set<Method>> signatureMap;  
       
      private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {  
        this.target = target;  
        this.interceptor = interceptor;  
        this.signatureMap = signatureMap;  
      }  
       
      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;  
      }  
       
      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);  
        }  
      }  
       
      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;  
      }  
       
      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()]);  
      }  
       
    }  

0 0
原创粉丝点击