mybatis的Interceptor机制

 更新时间:2023年09月06日 08:34:47   作者:codecraft  
这篇文章主要为大家介绍了mybatis的Interceptor机制源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下mybatis的Interceptor机制

Interceptor

org/apache/ibatis/plugin/Interceptor.java

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
  }
}
Interceptor定义了intercept方法,其参数为Invocation类型,同时默认提供了plugin方法,通过Plugin.wrap(target, this)进行包装

Invocation

org/apache/ibatis/plugin/Invocation.java

public class Invocation {
  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);
  }
}
Invocation定义了target、method、args属性,提供了proceed方法则是反射执行method方法

Plugin

org/apache/ibatis/plugin/Plugin.java

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);
    }
  }
  //......
}
Plugin实现了java.lang.reflect.InvocationHandler方法,其invoke方法主要是多了一层判断,判断interceptor的signatureMap有没有包含对应的方法,有则执行interceptor.intercept,同时包装了Invocation参数传递过去
而Plugin的wrap方法则是判断interceptor有没有拦截target对应的接口,如果有则通过Proxy.newProxyInstance返回代理对象方便后续进行拦截

InterceptorChain

org/apache/ibatis/plugin/InterceptorChain.java

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);
  }
}
InterceptorChain定义了interceptors,它提供了pluginAll方法对target代理所有的interceptor

Configuration

org/apache/ibatis/session/Configuration.java

protected final InterceptorChain interceptorChain = new InterceptorChain();
  public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
  }
Configuration定义了interceptorChain,它通过addInterceptor方法往interceptorChain添加interceptor

XMLConfigBuilder

org/apache/ibatis/builder/xml/XMLConfigBuilder.java

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);
      }
    }
  }
XMLConfigBuilder在解析xml的plugin的时候,会获取定义的interceptor,实例化之后通过configuration.addInterceptor添加进去

SqlSessionFactoryBean

org/mybatis/spring/SqlSessionFactoryBean.java

private Interceptor[] plugins;
  public void addPlugins(Interceptor... plugins) {
    setPlugins(appendArrays(this.plugins, plugins, Interceptor[]::new));
  }
  public void setPlugins(Interceptor... plugins) {
    this.plugins = plugins;
  }
  protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
    final Configuration targetConfiguration;
    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
      targetConfiguration = this.configuration;
      if (targetConfiguration.getVariables() == null) {
        targetConfiguration.setVariables(this.configurationProperties);
      } else if (this.configurationProperties != null) {
        targetConfiguration.getVariables().putAll(this.configurationProperties);
      }
    } else if (this.configLocation != null) {
      xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
      targetConfiguration = xmlConfigBuilder.getConfiguration();
    } else {
      LOGGER.debug(
          () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
      targetConfiguration = new Configuration();
      Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
    }
    Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
    Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
    Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
    //......
    if (!isEmpty(this.plugins)) {
      Stream.of(this.plugins).forEach(plugin -> {
        targetConfiguration.addInterceptor(plugin);
        LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
      });
    }
    if (hasLength(this.typeHandlersPackage)) {
      scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
          .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
          .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
    }
    if (!isEmpty(this.typeHandlers)) {
      Stream.of(this.typeHandlers).forEach(typeHandler -> {
        targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
        LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
      });
    }
    targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);
    //......
    return this.sqlSessionFactoryBuilder.build(targetConfiguration);
  }
SqlSessionFactoryBean的buildSqlSessionFactory方法在判断plugins不为空时,通过targetConfiguration.addInterceptor(plugin)将interceptor注册进去

MybatisAutoConfiguration

org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.java

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {
  private static final Logger logger = LoggerFactory.getLogger(MybatisAutoConfiguration.class);
  private final MybatisProperties properties;
  private final Interceptor[] interceptors;
  //......
  public MybatisAutoConfiguration(MybatisProperties properties, ObjectProvider<Interceptor[]> interceptorsProvider,
      ObjectProvider<TypeHandler[]> typeHandlersProvider, ObjectProvider<LanguageDriver[]> languageDriversProvider,
      ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider,
      ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
      ObjectProvider<List<SqlSessionFactoryBeanCustomizer>> sqlSessionFactoryBeanCustomizers) {
    this.properties = properties;
    this.interceptors = interceptorsProvider.getIfAvailable();
    this.typeHandlers = typeHandlersProvider.getIfAvailable();
    this.languageDrivers = languageDriversProvider.getIfAvailable();
    this.resourceLoader = resourceLoader;
    this.databaseIdProvider = databaseIdProvider.getIfAvailable();
    this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
    this.sqlSessionFactoryBeanCustomizers = sqlSessionFactoryBeanCustomizers.getIfAvailable();
  }
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    applyConfiguration(factory);
    if (this.properties.getConfigurationProperties() != null) {
      factory.setConfigurationProperties(this.properties.getConfigurationProperties());
    }
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      factory.setPlugins(this.interceptors);
    }
    //......
  }
MybatisAutoConfiguration的sqlSessionFactory方法,在判断interceptors不为空时,通过SqlSessionFactory的setPlugins方法把interceptors添加进去;MybatisAutoConfiguration标注了@Configuration注解,该注解标注了@Component,因而这些interceptors则是通过构造器从spring中注入的

Configuration.pluginAll

org/apache/ibatis/session/Configuration.java

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject,
      BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement,
        parameterObject, boundSql);
    return (ParameterHandler) interceptorChain.pluginAll(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);
    return (ResultSetHandler) interceptorChain.pluginAll(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);
    return (StatementHandler) interceptorChain.pluginAll(statementHandler);
  }
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : 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);
    }
    return (Executor) interceptorChain.pluginAll(executor);
  }

Configuration提供了newParameterHandler、newResultSetHandler、newStatementHandler、newExecutor方法,这些方法会对ParameterHandler、ResultSetHandler、StatementHandler、Executor执行interceptorChain.pluginAll方法,则创建作用了所有interceptor的代理对象,从而实现对这些对象的拦截效果

小结

  • mybatis的Interceptor机制使用的是jdk的Proxy.newProxyInstance的方式
  • 在扫描xml的时候把interceptor注册到configuration中,针对spring的场景,在MybatisAutoConfiguration中注入所有托管的interceptor,之后在构造SqlSessionFactory的时候把interceptor注册到configuration中
  • 最后Configuration提供了newParameterHandler、newResultSetHandler、newStatementHandler、newExecutor方法,创建作用了所有interceptor的代理对象,从而实现对这些对象的拦截效果

以上就是mybatis的Interceptor机制的详细内容,更多关于mybatis的Interceptor机制的资料请关注脚本之家其它相关文章!

相关文章

  • Java版的7种单例模式写法示例

    Java版的7种单例模式写法示例

    这篇文章主要给大家介绍了关于Java版的7种单例模式写法,文中通过示例代码介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-10-10
  • SpringBoot+WebSocket实现多人在线聊天案例实例

    SpringBoot+WebSocket实现多人在线聊天案例实例

    本文主要介绍了SpringBoot+WebSocket实现多人在线聊天案例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • 一篇文章带你了解java Object根类中关于toString,equals的方法

    一篇文章带你了解java Object根类中关于toString,equals的方法

    这篇文章主要介绍了Object类toString()和equals()方法使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2021-09-09
  • Spring Security实现基于角色的访问控制框架

    Spring Security实现基于角色的访问控制框架

    Spring Security是一个功能强大的安全框架,提供了基于角色的访问控制、身份验证、授权等安全功能,可轻松保护Web应用程序的安全,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-04-04
  • SpringBoot3集成MyBatis详解

    SpringBoot3集成MyBatis详解

    MyBatis是一款开源的持久层框架,它极大地简化了与数据库的交互流程,MyBatis更具灵活性,允许开发者直接使用SQL语句与数据库进行交互,本文将详细介绍在Spring Boot项目中如何集成MyBatis,以实现对数据库的轻松访问和操作,需要的朋友可以参考下
    2023-12-12
  • Java递归实现字符串全排列与全组合

    Java递归实现字符串全排列与全组合

    这篇文章主要为大家详细介绍了Java递归实现字符串全排列与全组合,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • maven安装配置的实现步骤

    maven安装配置的实现步骤

    本文主要介绍了maven安装配置的实现步骤,包括下载和安装Maven,配置Maven的环境变量,以及创建Maven项目,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • maven项目打jar包并包含所有依赖详细教程

    maven项目打jar包并包含所有依赖详细教程

    maven打包生成的普通jar包,只包含该工程下源码编译结果,不包含依赖内容,下面这篇文章主要给大家介绍了关于maven项目打jar包并包含所有依赖的相关资料,需要的朋友可以参考下
    2023-05-05
  • 详解Maven私服Nexus的安装与使用

    详解Maven私服Nexus的安装与使用

    这篇文章主要介绍了详解Maven私服Nexus的安装与使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • Mybatis实体类和表映射问题(推荐)

    Mybatis实体类和表映射问题(推荐)

    在项目开发中我们经常会遇到表中的字段名和表对应实体类的属性名称不一定都是完全相同的。下面小编给大家介绍下这种情况下如何解决字段名与实体类属性名不相同的冲突问题。下面小编给大家带来了Mybatis实体类和表映射的解决方法,小伙伴们一起学习吧
    2016-09-09

最新评论