一、 mybatis插件是啥
答:是拦截器(底层动态代理实现)
总共提供四大组件
Executor
StatementHandler
ParameterHandler
ResultSetHandler
你只能做这四大组件的插件。
mybatis插件就是拦截器。这个拦截器底层用动态代理实现。
二、 mybatis插件初始化
InterceptorChain在mybatis配置文件被解析的时候被初始化
InterceptorChain主要是一个arrayList
private final List interceptors = new ArrayList<>();
具体的每一个插件从配置文件中的这种形态
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
//省略
</plugin>
</plugins>
转化为InterceptorChain 中的Interceptor经历以下流程:
mybatis插件机制源码
二、自定义 mybatis插件
@Intercepts({
@Signature(
//此处写需要拦截的类名(就是文章开头提到的四大组件)
type = Executor.class,
//需要拦截的方法名
method = "query",
//方法中对应的参数
args ={MappedStatement .class, Object .class, RowBounds .class, ResultHandler .class}
)})
//在这个方法中写对应的增强逻辑
@Override
public Object intercept(Invocation invocation) throws Throwable {
//方法增强
System.out.println("此处方法增强");
//invocation.proceed()对应原先逻辑
return invocation.proceed();
}