mybatis 拦截器的理解

1.明白怎么拦截,都能拦截什么

    使用Plugins(插件)

    <!-- 插件配置 -->
<plugins>
<plugin interceptor="..../MyInterceptor" />
    </plugins>

      使用方法   定义一个类实现Interceptor接口,通过@intercepts注解指定想要拦截方法的签名

      type :拦截的接口是 4个代理接口  Executor、StatementHandler、ParameterHandler和ResultSetHandler     

    method:监听的方法 query

    arg: 参数(query(arg))

       一个MappedStatement对象对应Mapper配置文件中的一个select/update/insert/delete节点,主要描述的是一条SQL语句

          (详解网址:http://blog.csdn.net/ashan_li/article/details/50351080)

      Object调用节点时传入的参数

    @Intercepts(@Signature(args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}, method = "query", type =StatementHandler.class))

    public class MyInterceptor  implements Interceptor{

      private String dataBaseType;
@Override
public Object intercept(Invocation invocation) throws Throwable {

return  invocation;
}
@Override
public Object plugin(Object target) {

     /**

      plugin 是一个动态代理类,MyInterceptor 是真实对象

       当调用Plugin.wrap的静态方法的时候 回现走动态代理类的invoke方法

    **/

    return Plugin.wrap(target, this);

}
@Override
public void setProperties(Properties properties) {

      //获取mapped里面的属性值

    this.dataBaseType= properties.getProperty("");
}
}

   动态代理类plugin,继承一个InvocationHandler接口该接口只有一个实现方法invock

proxy:指代我们所代理的那个真实对象

method:指代的是我们所要调用真实对象的某个方法的Method对象

args:指代的是调用真实对象某个方法时接受的参数

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

Proxy这个类的作用就是用来动态创建一个代理对象的类,它提供了许多的方法,但是我们用的最多的就是 newProxyInstance 这个方法:

    (使用场景  有多个真实代理类 可以通过强转类型来调用不同的真实代理类的方法)

(  Proxy.newProxyInstance 创建的代理对象是在jvm运行时动态生成的一个对象,它并不是我们的InvocationHandler类型,也不是我们定义的那组接口的类型,而是在运行是动态生成的一个对象,并且命名方式都是这样的形式,以$开头,proxy为中,最后一个数字表示对象的标号)

  public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException

loader:  一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载


interfaces:  一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如
果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了


h:  一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上

    参考网址 http://blog.csdn.net/u012089657/article/details/49763631

                   https://www.cnblogs.com/xiaoluo501395377/p/3383130.html


     

   

                  

猜你喜欢

转载自blog.csdn.net/qq_33458228/article/details/78788392