mybatis中如何编写一个自定义插件?
下文笔者讲述mybatis中编写自定义插件的方法分享,如下所示
Mybatis实现自定义插件的示例分享
Mybatis自定义插件主要借助Mybatis四大对象: (Executor、StatementHandler 、ParameterHandler 、ResultSetHandler)进行拦截 Executor:拦截执行器的方法(log记录) StatementHandler:拦截Sql语法构建的处理 ParameterHandler:拦截参数的处理 ResultSetHandler:拦截结果集的处理例:
Mybatis实现自定义插件的示例分享
Mybatis自定义插件必须实现Interceptor接口
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
intercept方法:拦截器具体处理逻辑方法
plugin方法:根据签名signatureMap生成动态代理对象
setProperties方法:设置Properties属性
自定义插件demo
// ExamplePlugin.java
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget(); //被代理对象
Method method = invocation.getMethod(); //代理方法
Object[] args = invocation.getArgs(); //方法参数
// do something ...... 方法拦截前执行代码块
Object result = invocation.proceed();
// do something .......方法拦截后执行代码块
return result;
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
一个@Intercepts
可以配置多个@Signature,
@Signature中的参数定义如下
type:表示拦截的类,这里是Executor的实现类
method:表示拦截的方法,这里是拦截Executor的update方法
args:表示方法参数
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


