MyBatis——拦截器

MyBatis——拦截器

八月 19, 2019

Mybatis核心对象

1.ParameterHandler:处理sql的参数对象
2.ResultSetHandler:处理sql的返回结果集
3.StatementHandler:数据库的处理对象,用于执行sql语句
4.Executor:Mybatis的执行器,用于执行增删改查操作

Mybatis插件接口——Intercept(实现拦截器)

1.Intercept方法,插件的核心方法
2.使plugin方法,生成target的代理对象
3.setProperties方法,配置所需参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Created by imooc
* 插件签名,告诉mybatis单钱插件用来拦截那个对象的哪个方法
* type:拦截的对象,method:拦截对象的方法 args:方法的参数
*/
@Intercepts({
@Signature(type = ResultSetHandler.class,method ="handleResultSets",args = Statement.class)
})
public class MyFirstInterceptor implements Interceptor {

//拦截目标对象的目标方法的
public Object intercept(Invocation invocation) throws Throwable {
//invocatio n.getTarget()得到所拦截的目标对象
System.out.println("first plugin Intercept:"+invocation.getTarget());
//invocation.getMethod()得到所拦截的方法
System.out.println(invocation.getMethod());
//invocation.getArgs()得到所拦截的方法的参数
System.out.println(invocation.getArgs());
//执行目标对象方法
Object object=invocation.proceed();
return object;
}

//包装目标对象 为目标对象创建代理对象的
//Object对象就是拦截器拦截的对象
public Object plugin(Object o) {
System.out.println("first plugin :"+o);
//将对象进行包装
return Plugin.wrap(o,this);
}

//获取配置文件的属性:属性值值在配置文件中设置
public void setProperties(Properties properties) {
System.out.println("first plugin :"+properties);
}
}
1
2
3
4
5
  将拦截器配置到全局文件当中
<plugin interceptor="com.mooc.mybatis.interceptor.MyFirstInterceptor">
配置文件中设置参数
<property name="hello" value="world"></property>
</plugin>

多插件的开发过程

1.创建代理的时候,按照插件配置的顺序进行包装
2.执行目标方法后,是按照代理的逆向进行执行