mybatis源码分析:阅读Mybatis插件原理及应用笔记

Scroll Down

1、Mybatis插件实现原理

在Mybatis主配置文件中,可以通过plugins标签注册用户自定义的插件信息。
例如:

<plugins>
    <plugin interceptor="org.mybatis.example.ExamplePlugin">
        <property name="someProperty" value="100"/>
    </plugin>
</plugins>

Mybatis的插件实际上就是一个拦截器,Configuration类中维护了一个InterceptorChain的实例。

protected final InterceptorChain interceptorChain = new InterceptorChain();

interceptorChain属性是一个拦截器链,用于存放通过plugins标签注册的所有拦截器,Configuration类中还定义了addInterceptor()方法,用于向拦截器链中添加拦截器。Mybatis框架在应用启动时会对plugins标签进行解析。

private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // 获取plugin标签的interceptor属性。
        String interceptor = child.getStringAttribute("interceptor");
        // 获取拦截器属性,转换为Properties对象
        Properties properties = child.getChildrenAsProperties();
        // 创建拦截器实例
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        // 设置拦截器实例属性信息
        interceptorInstance.setProperties(properties);
        // 将拦截器实例添加到拦截器链中
        configuration.addInterceptor(interceptorInstance);
      }
    }
}

到此为止,拦截器的注册过程已经分析完毕。接下来看下拦截器的执行过程。
用户自定义的插件只能对Mybatis中的4种组件的方法进行拦截,这4种组件及方法如下:
(1)、Executor
(2)、ParameterHandler
(3)、ResultSetHandler
(4)、StatementHandler
Configuration组件有3个作用:
(1)、用于描述Mybatis配置信息,项目启动时,Mybatis的所有配置信息都被转换为Configuration对象。
(2)、作为中介者简化Mybatis各个组件之间的交互,解决了各个组件错综复杂的调用关系,属于中介者模式的应用。
(3)、作为Executor、ParameterHandler、ResultSetHandler、StatementHandler组件工厂创建这些组件的实例。
Mybatis使用工厂方法创建Executor、ParameterHandler、ResultSetHandler、StatementHandler组件的实例,其中一个原因是可以根据用户配置的参数创建不同的实现类的实例;另一个比较重要的原因就是可以在工厂方法中执行拦截逻辑。

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    // 创建ParameterHandler代理对象
    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 = (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 = (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 = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

在这些工厂方法中,都调用了InterceptorChain对象的pluginAll()方法,pluginAll()方法返回Executor、ParameterHandler、ResultSetHandler、StatementHandler对象的代理对象,拦截逻辑都是在代理对象中完成的。
InterceptorChain类的实现如下:

public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  // 调用所有拦截器对象的plugin()方法执行拦截逻辑
  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);
  }

}

Mybatis中所有用户自定义的插件都必须实现Interceptor接口,该接口的定义如下:

public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  Object plugin(Object target);

  void setProperties(Properties properties);

}

Interceptor接口中定义了3个方法,interceptor()方法用于自定义拦截逻辑,该方法会在目标方法调用时执行。plugin()方法用于创建Executor、ParameterHandler、ResultSetHandler、StatementHandler的代理对象,该方法参数即为Executor、ParameterHandler、ResultSetHandler、StatementHandler组件的实例。setProperties()方法用于设置插件的属性值。需要注意的是,intercept()接收一个Invocation对象作为参数,Invocation对象中封装了目标对象的方法及参数信息Invocation类的代码如下:

public class Invocation {
  // 目标对象Executor、ParameterHandler、ResultSetHandler、StatementHandler
  private final Object target;
  // 目标方法,即拦截方法
  private final Method method;
  // 目标方法参数
  private final 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;
  }

  // 执行目标方法
  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}

Mybatis中提供了一个plugin工具类,代码如下

public class Plugin implements InvocationHandler {

  private final Object target;
  private final Interceptor interceptor;
  private final 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) {
    // 调用getSignatureMap方法获取自定义插件中,通过Intercepts注解指定的方法。
    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;
  }

  @Override
  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 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()]);
  }

}

Intercepts注解修饰拦截器类,告诉拦截器要对哪些组件的方法进行拦截。

private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    // 获取Intercepts注解信息
    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>>();
    // 对所有Signature注解进行遍历,把Signature注解指定拦截的组件及方法添加到Map中
    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;
}

当需要自定义一个Mybatis插件时,只需要实现Interceptor接口,在intercept()方法中编写拦截逻辑,通过plugin()方法返回一个动态代理对象,通过setProterties()方法设置plugin标签中配置的属性值即可。
最后,整体看下Mybatis插件的工作原理。以执行一个查询操作为例。SqlSession是Mybatis中通过工厂模式创建Executor实例,Configuration类中提供了一个newExecutor()工厂方法,该方法返回的实际上是一个Executor的动态代理对象。
(1)、SqlSession中会调用Configuration类提供的newExecutor工厂方法创建Executor对象。
(2)、Configuration类中通过一个InterceptorChain对象维护了用户自定义的拦截器链。newExecutor()方法中调用InterceptorChain对象的pluginAll()方法。
(3)、自定义拦截器的plugin()方法是由用户来编写的,通常会调用Plugin类的wrap()静态方法创建一个代理对象。
执行过程如下:
(1)、SqlSession操作数据库需要依赖于Executor组件,SqlSession会调用Configuration对象的newExecutor方法获取Executor的实例。
(2)、SqlSession获取到的是Executor组件的代理对象,执行查询操作时会调用代理对象的query()方法。
(3)、按照JDK动态代理机制,调用Executor代理对象的query()方法时,会调用Plugin类的invoke()方法。
(4)、Plugin类的invoke()方法中会调用自定义拦截器对象的intercept()方法执行拦截逻辑。
(5)、自定义拦截器对象的intercept()方法调用完毕后,调用目标Executor对象的query()方法。
(6)、所有操作执行完毕后,会将查询结果返回给SqlSession对象。