zoukankan      html  css  js  c++  java
  • Mybatis拦截器(插件实现原理)

    在mybatis的mybatis.cfg.xml中插入:
        <plugins>
            <plugin interceptor="cn.sxt.util.PageInterceptor"/>
        </plugins>
        <mappers>
            <mapper resource="cn/sxt/vo/user.mapper.xml"/>
        </mappers>
     
    对于Executor,Mybatis中有几种实现:BatchExecutor、ReuseExecutor、SimpleExecutor和CachingExecutor。
    这个时候如果你觉得这几种实现对于Executor接口的query方法都不能满足你的要求,那怎么办呢?是要去改源码吗?当然不。
    我们可以建立一个Mybatis拦截器用于拦截Executor接口的query方法,在拦截之后实现自己的query方法逻辑,
    之后可以选择是否继续执行原来的query方法。
    public interface Interceptor {
      Object intercept(Invocation invocation) throws Throwable;
      Object plugin(Object target);
      void setProperties(Properties properties)
    }
     
    plugin方法是拦截器用于封装目标对象的,通过该方法我们可以返回目标对象本身,也可以返回一个它的代理。
    setProperties方法是用于在Mybatis配置文件中指定一些属性的。
    @Intercepts用于表明当前的对象是一个Interceptor,
    @Signature则表明要拦截的接口、方法以及对应的参数类型。

     
    @Intercepts( {
           @Signature(method = "query", type = Executor.class, args = {
                  MappedStatement.class, Object.class, RowBounds.class,
                  ResultHandler.class }),
           @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) })
     
     
    @Intercepts标记了这是一个Interceptor,然后在@Intercepts中定义了两个@Signature,即两个拦截点。
    @Signature我们定义了该Interceptor将拦截Executor接口中参数类型为MappedStatement、Object、RowBounds和ResultHandler的query方法;
    第二个@Signature我们定义了该Interceptor将拦截StatementHandler中参数类型为Connection的prepare方法。
     
    只能拦截四种类型的接口:Executor、StatementHandler、ParameterHandler和ResultSetHandler。(动态代理模式)
    拦截器实现Mybatis分页的一个思路就是拦截StatementHandler接口的prepare方法,
  • 相关阅读:
    【poj2761】 Feed the dogs
    【bzoj1086】 scoi2005—王室联邦
    学堂在线
    【bzoj3757】 苹果树
    【uoj58】 WC2013—糖果公园
    博弈论学习笔记
    【poj2960】 S-Nim
    【poj2234】 Matches Game
    【poj1740】 A New Stone Game
    【bzoj1853】 Scoi2010—幸运数字
  • 原文地址:https://www.cnblogs.com/shuchen007/p/9250599.html
Copyright © 2011-2022 走看看