Mybatis intercepter 扩展点生效原理

news/2024/7/24 12:34:12 标签: mybatis, java, 开发语言

1、

MybatisSqlSessionFactoryBean 通过 setPlugins 添加插件

2、buildSqlSessionFactory()   给Configuration添加插件

if (!isEmpty(this.plugins)) {
    Stream.of(this.plugins).forEach(plugin -> {
        targetConfiguration.addInterceptor(plugin);
        LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
    });
}
public void addInterceptor(Interceptor interceptor) {
  interceptorChain.addInterceptor(interceptor);
}

Configuration持有  InterceptorChain interceptorChain = new InterceptorChain();

 

3、Configuration 有5个方法分别创建 ParameterHandler、ResultSetHandler、StatementHandler、Executor。

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;
}

到此可以看到 ParameterHandler、ResultSetHandler、StatementHandler、Executor都会通过

interceptorChain.pluginAll 进行加强。

4、InterceptorChain 可以看到,配置的每一个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);
  }

}
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
  }

}

代码中可以看到,加强是通过Plugin类进行。Plugin 实现了InvocationHandler接口,可以推测,这块采用的是jdk的动态代理。wrap时

1、从当前Interceptor获取Intercepts以及其中的Signature注解获取要拦截的类以及方法

构造Map<Class<?>, Set<Method>> signatureMap

2、getAllInterfaces方法,从当前target 获取需要拦截的接口

3、Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap));创建代理对象

4、

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) {
    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 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[] 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 {
        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<>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[0]);
  }

}


http://www.niftyadmin.cn/n/355770.html

相关文章

Flink用户自定义连接器(Table API Connectors)学习总结

文章目录 前言背景官网文档概述元数据解析器运行时的实现 自定义扩展点工厂类Source扩展Sink和编码与解码 自定义flink-http-connectorSQL示例具体代码pom依赖HttpTableFactoryHttpTableSourceHttpSourceFunctionHttpClientUtil 最后参考资料 前言 结合官网文档和自定义实现一…

【ChatgGPT】ChatgGPT生成Excel提取字符公式

参考视频&#xff1a;https://edu.csdn.net/learn/38346/613668 问题场景&#xff1a;网站用户发帖统计excel表中&#xff0c;C,D,E.F列有每个用户每周发布的文章数量&#xff0c;只有每周发布文章都至少2篇及以上的才有奖品。如何写excel公式来找出符合条件的人? 1.下载所需…

es 二、核心概念

目录 Nrt cluster集群概念 node节点 Document 文档 Index 索引 Field字段 Type 类型 shard分片 Replica shard副本 数据库和es概念对比 Nrt 写入一秒后就能搜到 cluster集群概念 一台机器启动一个实例即可&#xff0c;多个组成 node节点 一个实例一个节点 Documen…

AttributeError: module ‘gym‘ has no attribute ‘benchmark_spec‘解决办法

报错如下&#xff1a; 我安装的gym版本是gym-0.26.2 报错原因&#xff1a;gym版本太高了&#xff0c;需要降低版本 pip install gym0.9.0 -i https://pypi.douban.com/simple

机器学习基础(二)-具体分类模型【未完待续】

一、感知机 占坑 二、KNN kd树的搜索过程到底是怎么进行的&#xff1f; - 月来客栈的文章 - 知乎

JVM 问题整理

JVM内存模型 程序计数器:当前线程所执行的字节码的行号指示器,用于记录正在执行的虚拟机字节指令地址,线程私有。 虚拟机栈:存放基本数据类型、对象的引用、方法出口等,线程私有。 本地方法栈:和虚拟栈相似,只不过它服务于Native方法,线程私有 Java堆:java内存最大的一块,所有对…

【算法刷题】树和二叉树题型及方法归纳

1、树和二叉树的特点 &#xff08;1&#xff09;二叉树 二叉树是有左、右孩子的树&#xff0c;存储方式有顺序存储和链式存储。 二叉树的链式存储 struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNod…

传染病学模型 | Matlab实现SEIR传染病学模型 (SEIR Epidemic Model)

文章目录 效果一览基本描述模型介绍程序设计参考资料效果一览 基本描述 传染病学模型 | Matlab实现SEIR传染病学模型 (SEIR Epidemic Model) 模型介绍 SEIR模型是一种常见的传染病传播模型,用于描述人群感染某种传染病的过程。SEIR模型将人群划分为四个互相转化的状态: 易感者…