1、编写自己的插件类
1)实现 Interceptor 接口
这个是所有的插件必须实现的接口。
2)添加@Intercepts({@Signature()}),指定拦截的对象和方法、方法参数
方法名称+参数类型,构成了方法的签名,决定了能够拦截到哪个方法。
问题:拦截签名跟参数的顺序有关系吗?
3)实现接口的 3 个方法
// 用于覆盖被拦截对象的原有方法(在调用代理对象 Plugin 的 invoke()方法时被调用)
Object intercept(Invocation invocation)
throws
Throwable;
// target 是被拦截对象,这个方法的作用是给被拦截对象生成一个代理对象,并返回它
Object plugin(Object target);
// 设置参数
void
setProperties(Properties properties);
2、插件注册,在 mybatis-config.xml 中注册插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="offsetAsPageNum" value="true"/>
……后面全部省略……
</plugin>
</plugins>
3、插件登记
MyBatis 启 动 时 扫 描 <plugins> 标 签 , 注 册 到 Configuration 对 象 的
InterceptorChain 中。property 里面的参数,会调用 setProperties()方法处理。
以上就是编写和使用自定义插件的全部步骤。
4. 案例
自定义拦截器
@Intercepts({ @Signature(type = StatementHandler.class, method = "query", args = { Statement.class, ResultHandler.class}) })
@Slf4j
public class SQLInterceptor implements Interceptor {
private Properties properties;
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
log.info("{}获取到SQL语句:{}",properties.getProperty("serverName"),sql);
try {
return invocation.proceed();
}finally {
long endTime = System.currentTimeMillis();
log.info("SQL执行耗时:{} ms", (endTime-startTime));
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
this.properties=properties;
}
}
添加到配置中
<plugins>
<plugin interceptor="com.gupaoedu.interceptor.MyPageInterceptor">
</plugin>
</plugins>-->
或者通过配置类
Properties sqlProperties = new Properties();
sqlProperties.setProperty("serverName","testServer");
sqlInterceptor.setProperties(sqlProperties);
sessionFactory.setPlugins(new Interceptor[] {interceptor,sqlInterceptor});