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:表示方法参数
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)