Mybatis 拦截器(一)

1、编写自定义拦截器类
@Intercepts({
@Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) 
})
public class MyInterceptor implements Interceptor {
 
public Object intercept(Invocation invocation) throws Throwable {
RoutingStatementHandler handler =
(RoutingStatementHandler) invocation.getTarget();
 /**通过反射获取到当前RoutingStatementHandler对象的delegate属性  */      
    StatementHandler delegate =
(StatementHandler)ReflectUtil.getFieldValue(handler, "delegate");
 
      /*获取到当前StatementHandler的 boundSql,因为之前已经说过了,RoutingStatementHandler实现的StatementHandler接口方法里面调用的delegate对应的方法*/ 
    BoundSql boundSql = delegate.getBoundSql();  /**拿到当前绑定Sql的参数对象,就是我们在调用对应的Mapper映射语句时所传入的参数对象  */
          Object param = bs.getParameterObject();
String sql = bs.getSql();
if (param instanceof HashMap) {//param 已是hashMap,验证dao中接口方法的传入参数 是否含有分页标示
HashMap map = (HashMap) param;
PageList p = (PageList) map.get(PAGE_KEY);
if (p != null) {
/*p.setCount(queryTotal(ivk, ms, bs, param, sql));--分页sql 拼写逻辑
set(p);
ReflectHelper.setValueByFieldName(bs, "sql", pageSql(sql, p));*/
}
}
      return invocation.proceed();  
}
 
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
/**
* 设置初始化变量
*/
public void setProperties(Properties arg0) {
System.out.println("set begin....");
}
 
}

2、在mybatis-confg.xml 中初始化参数并 在sqlsessionfactory 中注册拦截器
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
<plugins>
<!-- <plugin interceptor="com.common.page.ResultSetInterceptor" /> -->
<plugin interceptor="com.tool.MyInterceptor">
<!-- <property name="dialect" value="oracle" /> -->
</plugin>
</plugins>
</configuration>

<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation"
value="classpath:config/mybatis-config.xml">
</property>
<property name="dataSource" ref="dataSource" />
</bean>
原文地址:https://www.cnblogs.com/leonkobe/p/3522713.html