Configuration和Interceptor是mybatis中最重要的两个类,Configuration是mybatis中所有数据的载体,包括mybatis配置信息、mapper.xml文件中sql等都存储在Configuration中。而Interceptor则是扩展mybatis功能最重要的接口。
Mybatis通过Interceptor为我们提供了扩展ParameterHandler、ResultSetHandler、StatementHandler、Executor的能力。本章我们介绍Interceptor。首先来看官方给出的example:
1 | java复制代码@Intercepts({ |
上面就是Interceptor最简单的使用方法。
使用Interceptor需要了解的5个类:Interceptor、@Intercepts、@Signature、InterceptorChain、Plugin。
Interceptor
Interceptor是开发者需要去实现的接口,主要实现intercept方法,来定义对代理方法的代理逻辑。其接口定义如下:
1 | java复制代码public class Invocation { |
@Intercepts、@Signature
注解在Interceptor实现类上,用来指定需要被代理的方法。
1 | java复制代码@Documented |
需要说明的是虽然上面例子实现了对Map类的代理,但是在Mybatis中一般只对ParameterHandler、ResultSetHandler、StatementHandler、Executor这4个类进行代理。
Plugin
Mybatis提供的默认代理工厂类。
1 | java复制代码public class Plugin implements InvocationHandler { |
InterceptorChain
用来存储多个Interceptor:
1 | java复制代码public class InterceptorChain { |
本文转载自: 掘金