我们首先介绍一下Mybatis插件相关的几个类,并对源码进行了简单的分析。

Mybatis插件相关的接口或类有:Intercept、InterceptChain、Plugin和Invocation,这几个接口或类实现了整个Mybatis插件流程。

Interceptor:一个接口,是实现自己功能需要实现的接口

源码如下:

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

  //在此方法中实现自己需要的功能,最后执行invocation.proceed()方法,实际就是调用method.invoke(target, args)方法,调用代理类
  Object intercept(Invocation invocation) throws Throwable;

  //这个方法是将target生成代理类
  Object plugin(Object target);
  //在xml中注册Intercept是配置一些属性
  void setProperties(Properties properties);

}

InterceptorChain:有一个List<Interceptor> interceptors变量,来保存所有Interceptor的实现类

源码如下:

/**
 * @author Clinton Begin
 */
public class InterceptorChain {

  //插件拦截器链
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  //把target变成代理类,这样在运行target方法之前需要运行Plugin的invoke方法
  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);
  }

}

Invocation:一个比较简单的类,主要的功能就是根据构造函数类执行代理类

源码如下:

/**
 * @author Clinton Begin
 */
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;
  }
  //其实mybatis的Interceptor最终还是调用的method.invoke方法
  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}

Plugin:Mybatis插件的核心类,它实现了代理接口InvocationHandler,是一个代理类

源码详解如下:

/**
 * @author Clinton Begin
 */
//这个类是Mybatis拦截器的核心,大家可以看到该类继承了InvocationHandler
//又是JDK动态代理机制
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) {
	//首先根据interceptor上面定义的注解 获取需要拦截的信息
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
	//如果长度为>0 则返回代理类 否则不做处理
    if (interfaces.length > 0) {
	  //创建JDK动态代理对象
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  //在执行Executor、ParameterHandler、ResultSetHandler和StatementHandler的实现类的方法时会调用这个方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
	  //通过method参数定义的类 去signatureMap当中查询需要拦截的方法集合
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
	  //判断是否是需要拦截的方法,如果需要拦截的话就执行实现的Interceptor的intercept方法,执行完之后还是会执行method.invoke方法,不过是放到interceptor实现类中去实现了
      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)实现类上面的注解获取相关信息
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
	//获取注解信息
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
	//为空则抛出异常
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
	//获得Signature注解信息
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
	//循环注解信息
    for (Signature sig : sigs) {
	  //根据Signature注解定义的type信息去signatureMap当中查询需要拦截方法的集合
      Set<Method> methods = signatureMap.get(sig.type());
	  //第一次肯定为null 就创建一个并放入signatureMap
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
		//找到sig.type当中定义的方法 并加入到集合
        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;
  }
  //根据对象类型与signatureMap获取接口信息
  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
	//循环type类型的接口信息 如果该类型存在与signatureMap当中则加入到set当中去
    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()]);
  }

}

对Mybatis插件有一定了解的人应该知道,插件拦截的类是Executor、ParameterHandler、ResultSetHandler和StatementHandler的实现类,为什么会这样呢?在Configuration类中看一下代码就明白了,可以看到在初始化Executor、ParameterHandler、ResultSetHandler和StatementHandler都会调用interceptorChain.pluginAll()这个函数,其实这样之后各个接口的实现类就被代理类生成为目标类了。

 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) {
    return newExecutor(transaction, defaultExecutorType);
  }

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    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);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

Mybatis插件原理分析(一)的更多相关文章

  1. Mybatis插件原理分析(二)

    在上一篇中Mybatis插件原理分析(一)中我们主要介绍了一下Mybatis插件相关的几个类的源码,并对源码进行了一些解释,接下来我们通过一个简单的插件实现来对Mybatis插件的运行流程进行分析. ...

  2. Mybatis插件原理分析(三)分页插件

    在Mybatis中插件最经常使用的是作为分页插件,接下来我们通过实现Interceptor来完成一个分页插件. 虽然Mybatis也提供了分页操作,通过在sqlSession的接口函数中设置RowBo ...

  3. Mybatis框架(8)---Mybatis插件原理

    Mybatis插件原理 在实际开发过程中,我们经常使用的Mybaits插件就是分页插件了,通过分页插件我们可以在不用写count语句和limit的情况下就可以获取分页后的数据,给我们开发带来很大 的便 ...

  4. mybatis 插件原理

    [传送门]:mybatis 插件原理

  5. MyBATIS插件原理第一篇——技术基础(反射和JDK动态代理)(转)

    在介绍MyBATIS插件原理前我们需要先学习一下一些基础的知识,否则我们是很难理解MyBATIS的运行原理和插件原理的. MyBATIS最主要的是反射和动态代理技术,让我们首先先熟悉它们. 1:Jav ...

  6. Mybatis 插件原理解析

    SqlSessionFactory 是 MyBatis 核心类之一,其重要功能是创建 MyBatis 的核心接口 SqlSession.MyBatis 通过 SqlSessionFactoryBuil ...

  7. Spring + Mybatis 集成原理分析

    由于我之前是写在wizNote上的,迁移过来比较浪费时间,所以,这里我直接贴个图片,PDF文件我上传到百度云盘了,需要的可直接下载. 地址:https://pan.baidu.com/s/12ZJmw ...

  8. Mybatis的原理分析1(@Mapper是如何生效的)

    接着我们上次说的SpringBoot自动加载原理.我们大概明白了在maven中引入mybatis后,这个模块是如下加载的. 可能会有人问了,一般我们的dao层都是通过Mapper接口+Mapper.x ...

  9. MyBatis插件原理

    官方文档:https://mybatis.org/mybatis-3/zh/configuration.html#plugins MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用.默认 ...

随机推荐

  1. swiper实现臭美app滑动效果

    一.臭美app效果: 我的需求是这样,上面正常滑动,点击下面的小卡牌,上面的滑动区也随之切换到当前的点击态. 二.实现: css: 主要设置可见区域的几张卡牌的位置,注意的几个位置是,中间的激活态和左 ...

  2. linux加入Windows域-------本人生产环境上线所用

    为什么说要linux加域呢!    因为之前在公司是做vmware的,然后呢vmware的horizon桌面云虚拟化都是通过域来管理的,开始使用的都是Windows桌面,后来开发的人员说要使用linu ...

  3. 修复 Ubuntu 14.04 的系统设置残缺问题

    sudo apt-get install ubuntu-desktop

  4. exp和imp的使用场合

    1.检测冲突 使用exp工具,在数据库中预先检测到物理或逻辑冲突. 导出的同时,将全扫描数据库中的每张表,读出所有行.如果某处表中有个损坏的块,必然能找到它. 2.可以用来快速恢复数据库. 使用exp ...

  5. python 循环和file操作实现用户密码输错三次将用户锁定

    一.需求编写登录接口1.输入用户名密码2.认证成功后显示欢迎信息3.输错三次后锁定 二.简单思路登录,三次密码输入错误锁定用户1.用户信息文件:存放用户名和密码2.黑名单文件:将输入三次错误的用户加入 ...

  6. Docker常见仓库MongoDB

    MongoDB 基本信息 MongoDB 是开源的 NoSQL 数据库实现. 该仓库提供了 MongoDB 2.2 ~ 2.7 各个版本的镜像. 使用方法 默认会在 27017 端口启动数据库. $ ...

  7. 防止SpringMVC拦截器拦截js等静态资源文件

    SpringMVC提供<mvc:resources>来设置静态资源,但是增加该设置如果采用通配符的方式增加拦截器的话仍然会被拦截器拦截,可采用如下方案进行解决: 方案一.拦截器中增加针对静 ...

  8. SpringMVC+Spring+Mybatis整合,使用druid连接池,声明式事务,maven配置

    一直对springmvc和mybatis挺怀念的,最近想自己再搭建下框架,然后写点什么. 暂时没有整合缓存,druid也没有做ip地址的过滤.Spring的AOP简单配置了下,也还没具体弄,不知道能不 ...

  9. Programming In Scala笔记-第十六章、Scala中的List

    本章主要分析Scala中List的用法,List上可进行的操作,以及需要注意的地方. 一.List字面量 首先看几个List的示例. val fruit = List("apples&quo ...

  10. High Executions Of Statement "delete from smon_scn_time..."

    In this Document   Symptoms   Cause   Solution APPLIES TO: Oracle Database - Enterprise Edition - Ve ...