Mybatis那些事-拦截器(Plugin+Interceptor)


Mybatis的拦截器实现机制,使用的是JDK的InvocationHandler.
当我们调用ParameterHandler,ResultSetHandler,StatementHandler,Executor的对象的时候,
实际上使用的是Plugin这个代理类的对象,这个类实现了InvocationHandler接口.
接下来我们就知道了,在调用上述被代理类的方法的时候,就会执行Plugin的invoke方法.
Plugin在invoke方法中根据@Intercepts的配置信息(方法名,参数等)动态判断是否需要拦截该方法.
再然后使用需要拦截的方法Method封装成Invocation,并调用Interceptor的proceed方法.
这样我们就达到了拦截目标方法的结果.
例如Executor的执行大概是这样的流程:
拦截器代理类对象->拦截器->目标方法
Executor->Plugin->Interceptor->Invocation
Executor.Method->Plugin.invoke->Interceptor.intercept->Invocation.proceed->method.invoke



注解
@Intercepts 在实现Interceptor接口的类声明,使该类注册成为拦截器
  Signature[] value//定义需要拦截哪些类,哪些方法
@Signature 定义哪些类(4种),方法,参数需要被拦截
  Class<?> type()//ParameterHandler,ResultSetHandler,StatementHandler,Executor
  String method()//
  Class<?>[] args()//

接口
Interceptor 实现拦截器的接口


InterceptorChain 拦截器链,保存了Mybatis配置的所有拦截器,保存在Configuration
  List<Interceptor> interceptors//拦截器

Invocation 类方法的一个封装,在拦截器中就是被调用的目标方法
  Object target//调用的对象
  Method method//调用的方法
  Object[] args//参数

Plugin 插件,其实就是ParameterHandler,ResultSetHandler,StatementHandler,Executor的代理类(Mybatis使用的JDK代理实现拦截器),实现了InvocationHandler接口
 Object target//被代理的目标对象
 Interceptor interceptor//拦截器
 Map<Class<?>, Set<Method>> signatureMap//接口需要拦截的方法(一对多,每个接口对应多个方法)
 //
 wrap(Object target, Interceptor interceptor)//把拦截器对象封装成Plugin代理对象.
 invoke(Object proxy, Method method, Object[] args)//
 

使用例子
1.写一个类,并且实现Interceptor接口
2.在上述类使用@Intercepts注解,配置拦截信息
3.在配置文件配置插件
@Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
        RowBounds.class, ResultHandler.class }) })
public class MyInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub

    }
}
配置文件加入
<plugins>
    <plugin interceptor="weber.mybatis.plugin.MyInterceptor" />
</plugins>


加入测试代码

public static void main(String[] args) throws IOException {

		String resource = "conf.xml";

		InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);

		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

		SqlSession session = sessionFactory.openSession();

		// User user = session.selectOne("weber.mybatis.mapper.getUser", 1);
		User userObj = new User();
		userObj.setId(123);
		session.selectList("weber.mybatis.mapper.searchByUser", userObj);

		// UserMapper mapper = session.getMapper(UserMapper.class);

		// mapper.selectAll();

		// System.out.println(user);
	}

开启debug模式,我们将看到Plugin是如何实现代理的.

当代码执行到下图红色部分的时候

将直接跳到下图!所以,我们此时的executor不是CachingExecutor对象,而是Plugin代理对象.


此时的method,就是被调用的目标方法如下:


最后附上源码注释

/**
 * @author Clinton Begin
 */
//Plugin是JDK动态代理类
public class Plugin implements InvocationHandler {

  private Object target;//目标对象(ParameterHandler,ResultSetHandler,StatementHandler,Executor)
  private Interceptor interceptor;//被代理的拦截器
  //目标类需要拦截的方法缓存.因为一个拦截器可以拦截多个类,一个类可以拦截多个方法.
  //所以用Map + Set的数据结构存储
  private Map<Class<?>, Set<Method>> signatureMap;//保存每个拦截器的@signature的配置信息

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }
  //把目标对象和拦截器封装成Plugin代理类实例.
  public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);//获取拦截器的拦截信息(需要拦截的类和方法)
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);//Proxy代理只能代理接口
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));//Plugin作为代理类,但是实际业务是由Interceptor拦截器完成的.
    }
    return target;
  }

  @Override
   //proxy,类代理的对象,例如CachingExecutor对象
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {//从这里代码看到,会拦截所有的Executor方法,动态的去判断拦截器要不要去拦截.所以要小心使用拦截器,会影响性能.
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
		//Invocation是目标对象,目标对象需要拦截的方法,我拦截方法的参数的封装.
        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);//获取拦截器注解@Signature
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    Signature[] sigs = interceptsAnnotation.value();//一个Signature表示一个拦截类型
	//保存需要拦截类的信息,class作为key, 需要拦截类的方法作为value集合Set保存.一个拦截器可以拦截一个类中多个方法
    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()]);
  }

}

/**
 * @author Clinton Begin
 */
//InterceptorChain里保存了所有的拦截器,它在mybatis初始化的时候创建。存在Configuration中
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);
  }

}

/**
 * @author Clinton Begin
 */
public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;//拦截方法,在这里处理拦截器的业务逻辑

  Object plugin(Object target);//把目标对象封装成Plugin对象

  void setProperties(Properties properties);

}


  • 14
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值