美文网首页
Spring+Mybatis学习之Plugin使用

Spring+Mybatis学习之Plugin使用

作者: Storydo | 来源:发表于2019-07-15 22:53 被阅读0次

    这里的Plugin不是开发工具中集成的插件,而是Mybatis中额外扩展功能使用到的插件,这个类所在的包都在plugin包下。这个原理比较简单,总共有7个类在该包下,其中一个PluginException异常类,抛出相关插件异常的。两个注解InterceptsSignature,其余四个类实现相关功能。插件实现相关功能的主要是其中的接口Interceptor,实现了该接口,然后将其注入到容器中,就能修改每条sql执行时的动作,如果操作不好,容易出现意想不到的结果,所以操作需要慎重。

    • Interceptor实现该接口即可拦截所有的sql操作
    • Intercepts 注解,用于注解到插件类上,参数决定拦截哪些类哪些方法
    • Signature 注解,与Intercepts搭配使用
    • Plugin 辅助实现一些识别,判断及生成代理对象相关功能

    注入容器

     public MapperAutoConfiguration(MybatisProperties properties,
                                        ObjectProvider<Interceptor[]> interceptorsProvider,
                                        ResourceLoader resourceLoader,
                                        ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                        ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {
            this.properties = properties;
            this.interceptors = interceptorsProvider.getIfAvailable();
            this.resourceLoader = resourceLoader;
            this.databaseIdProvider = databaseIdProvider.getIfAvailable();
            this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
        }
    

    这里还是上篇介绍的MapperAutoConfiguration类,通过配置注解,该类随着spring boot启动而注入,而容器中实现了Interceptor的所有类都会作为一个列表注入到容器中。
    MapperAutoConfiguration生成SqlSessionFactory的Bean时调用

     if (!ObjectUtils.isEmpty(this.interceptors)) {
                factory.setPlugins(this.interceptors);
     }
    

    SqlSessionFactory在构建时调用了如下代码保存相关插件,其实最终是保存在了配置类Configuration

    if (!isEmpty(this.plugins)) {
          for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
              LOGGER.debug("Registered plugin: '" + plugin + "'");
            }
          }
    

    该类中保存了几乎绝大部分mybatis需要用到的东西,在spring容器中,Configuration是单例,相关插件会保存到如下属性中。

      protected final InterceptorChain interceptorChain = new InterceptorChain();
    

    InterceptorChain内部很简单,一个List用来保存相关插件,而该类也在plugin包下,是刚才提到的7个类之一。

    插件实现Interceptor

    接下来看如果实现相关接口,制作一个插件。该接口也很简单,内部代码如下,没有过多说明。

    public interface Interceptor {
    
      Object intercept(Invocation invocation) throws Throwable;
    
      Object plugin(Object target);
    
      void setProperties(Properties properties);
    
    }
    

    实现类

    @Intercepts({@Signature(type= Executor.class,method = "update",args ={MappedStatement.class,Object.class})})
    public class ExamplePlugin implements Interceptor {
      private Properties properties = new Properties();
    
      public Object intercept(Invocation invocation) throws Throwable {
        // implement pre processing if need
        Object returnObject = invocation.proceed();
        // implement post processing if need
        return returnObject;
      }
      
        @Override
        public Object plugin(Object target) {
            return Plugin.wrap(target, this);
        }
    
      public void setProperties(Properties properties) {
        this.properties = properties;
      }
    }
    

    将该类注入到容器中

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

    spring boot中可以通过添加@Component注解,则该插件会自动注入,但是不能使用@Configuration注入,否则不能正常使用。

    插件拦截过程

    上边的代码会在Executor类执行所有的update操作时都经过此插件。而可以拦截的type类型有四种:

    • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
    • ParameterHandler (getParameterObject, setParameters)
    • ResultSetHandler (handleResultSets, handleOutputParameters)
    • StatementHandler (prepare, parameterize, batch, update, query)

    具体调用过程可以查看Configuration在创建这些对象是如何执行。这四个类中都执行了如下代码
    executor = (Executor) interceptorChain.pluginAll(executor);
    具体的入参和返回值是这四个类中的之一。然后在InterceptorChain中的pluginAll方法实际是循环调用了所有插件的plugin方法。也就是说以上四个类的所有方法都会经过我们插件中的plugin方法。而Plugin.wrap(target, this)这个方法才是识别相关注解中的类和方法。该方法会判断当前target是否为注解需要拦截的对象类型,如果是,为其生成相关代理对象返回。
    生成的代理对象调用的处理程序代码即为Plugin类中的invoke方法

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

    如果执行的方法是编写插件类注解中需要拦截的方法,则调用插件中的intercept方法,否则按原方法执行。
    这里Interceptor接口中的两个方法intercept和plugin,plugin用于替换拦截到的类,而intercept方法则是替换原有执行方法。这里代理执行有点绕,别的还好理解。

    相关文章

      网友评论

          本文标题:Spring+Mybatis学习之Plugin使用

          本文链接:https://www.haomeiwen.com/subject/dmjgkctx.html