Mybatis拦截器只能拦截四类对象,分别为:Executor、ParameterHandler、StatementHandler、ResultSetHandler,而SQL数据库的操作都是从Executor开始,因此要记录Mybatis数据库操作的耗时,需要拦截Executor类,代码实现如下:
/** * 数据库操作性能拦截器,记录耗时 * @Intercepts定义Signature数组,因此可以拦截多个,但是只能拦截类型为: * Executor * ParameterHandler * StatementHandler * ResultSetHandler * */ @Intercepts(value = { @Signature (type=Executor.class, method="update", args={MappedStatement.class,Object.class}), @Signature(type=Executor.class, method="query", args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class, CacheKey.class,BoundSql.class}), @Signature(type=Executor.class, method="query", args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})}) public class TimerInterceptor implements Interceptor { private static final Logger logger = Logger.getLogger(TimerInterceptor.class); /** * 实现拦截的地方 * */ @Override public Object intercept(Invocation invocation) throws Throwable { Object target = invocation.getTarget(); Object result = null; if (target instanceof Executor) { long start = System.currentTimeMillis(); Method method = invocation.getMethod(); /**执行方法*/ result = invocation.proceed(); long end = System.currentTimeMillis(); logger.info("[TimerInterceptor] execute [" + method.getName() + "] cost [" + (end - start) + "] ms"); } return result; } /** * Plugin.wrap生成拦截代理对象 * */ @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
完成上面的拦截后,需要将该类在Mybatis配置文件中声明,如下:
<plugins><!-- SQL性能拦截器 --><plugin interceptor="com.quar.interceptor.TimerInterceptor" /></plugins>
来源:http://www.cnblogs.com/hanfight/p/4752782.html