MyBatis插件

本文详细解释了MyBatis插件的工作原理,包括插件的注册过程、在Configuration类中的应用、如何生成拦截代理类以及执行拦截的机制,重点介绍了Interceptor、InterceptorChain和Plugin类的关键方法和功能。
摘要由CSDN通过智能技术生成

MyBatis插件

Mybatis插件原理

1. 注册插件(解析SqlMapConfig.xml时)

//XMLConfigBuilder类的parseConfiguration方法
private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      //解析插件  
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        String interceptor = child.getStringAttribute("interceptor");
        Properties properties = child.getChildrenAsProperties();
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
        interceptorInstance.setProperties(properties);
        //注册插件
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
  public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
  }
public class InterceptorChain {
  //插件列表
  private final List<Interceptor> interceptors = new ArrayList<>();
  //应用插件
  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);
  }

}

2. 应用插件

//Configuration类中
  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;
  }
public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<>();
  //应用拦截器,对目标对象进行拦截。target为ParameterHandler、ResultSetHandler、StatementHandler、Executor
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      //链式拦截
      //遍历所有插件,对target进行拦截后,返回值为target,target将被下一个拦截器拦截
      target = interceptor.plugin(target);
    }
    return target;
  }
}
/**
 * @author Clinton Begin
 */
public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;
  //拦截器拦截
  default Object plugin(Object target) {
      //拦截器拦截
    return Plugin.wrap(target, this);
  }

  default void setProperties(Properties properties) {
    // NOP
  }

}

3. 生成插件拦截代理类

//Plugin类中  
public static Object wrap(Object target, Interceptor interceptor) {
      //1.构建签名映射表signatureMap。
      //记录拦截器所关注的方法签名及其对应的拦截逻辑
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
      //2.确定目标对象接口
    Class<?> type = target.getClass();
      //找出所有需要被代理的接口
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
      //3.创建代理对象
    if (interfaces.length > 0) {
        //该类,在signatureMap中有需要被拦截的方法才生成代理类
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
  • 构建签名映射表
    • K:StatementHandler.class、Executor.class、ParameterHandler.class、ResultSetHandler.class
    • V:update, query, flushStatements, commit, rollback…等
//Plugin类中  
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
      //1.提取@Intercepts注解中的签名数组
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<Method> methods = MapUtil.computeIfAbsent(signatureMap, sig.type(), k -> new HashSet<>());
      try {
          //2.获取拦截的类的方法。该方法是最终被拦截的方法
        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类中
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
  Set<Class<?>> interfaces = new HashSet<>();
  while (type != null) {
    for (Class<?> c : type.getInterfaces()) {
      if (signatureMap.containsKey(c)) {
        interfaces.add(c);
      }
    }
    type = type.getSuperclass();
  }
  return interfaces.toArray(new Class<?>[0]);
}

4. 执行拦截

//Plugin是一个InvocationHandler
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;
  }

  //执行拦截
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
        //1.找到被拦截的方法
      if (methods != null && methods.contains(method)) {
          //2.执行拦截逻辑
          //interceptor.intercept方法由用户实现
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
}  

5. 小结

  1. 被拦截的类和方法

    拦截的类拦截的方法
    Executorupdate, query, flushStatements, commit, rollback,getTransaction, close, isClosed
    ParameterHandlergetParameterObject, setParameters
    StatementHandlerprepare, parameterize, batch, update, query
    ResultSetHandlerhandleResultSets, handleOutputParameters
  2. 代码执行链路

parseConfiguration-解析SqlMapConfig.xml
pluginElement-解析插件
configuration.addInterceptor-注册拦截器
interceptorChain.addInterceptor-加入拦截器列表
InterceptorChain.pluginAll-应用全部插件
Interceptor.plugin-组装递归式插件链
Plugin.wrap-组装单个插件
interceptorChain.pluginAll-拦截parameterHandler
interceptorChain.pluginAll-拦截resultSetHandler
interceptorChain.pluginAll-拦截statementHandler
interceptorChain.pluginAll-拦截executor
getSignatureMap-构建签名映射表
getAllInterfaces-需要被代理的接口
Proxy.newProxyInstance-创建代理
interceptsAnnotation.value-提取Intercepts注解中的签名数组
getMethod-获取拦截的类的方法.该方法是最终被拦截的方法
Plugin.invoke-触发代理类拦截
interceptor.intercept-用户自定义的插件拦截器方法
  • 19
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摸魚散人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值