根据网上资料我写了一个mybatis拦截器如下:
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (log.isInfoEnabled()) {
log.info("进入 LogUtil 拦截器...");
}
long startTime = System.currentTimeMillis();
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Configuration configuration = mappedStatement.getConfiguration();
Object returnVal = invocation.proceed();
// 获取sql语句
String sql = getSql(configuration, boundSql);
String params = getParams(configuration, boundSql);
String oldSql = boundSql.getSql().replaceAll("[\\s]+", " ");
printLog(returnVal, null);
log.info("用户ID:12345" + "," + "打印时间:" + sdf.format(new Date()) + "," + "调用方法:" + mappedStatement.getId() + ","
+ "原始sql:" + oldSql + "," + "完整SQL:" + sql + "," + "参数:" + params + "," + "查询结果" + returnVal.toString()
+ "," + "执行时间:" + (System.currentTimeMillis() - startTime) + "毫秒");
return returnVal;
}
由于拦截器打印sql需要自动执行在intercept方法中且此方法是重写的,我在外面的方法中可以获取到用户信息要怎么传入intercept方法中?
外部获取
public void save(AddDemoReqBO addDemoReqBO)
其中addDemoReqBO对象中包含了用户的信息,请问我怎么把这个对象传入拦截器中,或者有什么其他的方式可以实现打印出:谁在什么时候执行了什么sql 这样的日志?
最简单的方法,你的用户应该在session中,这里可以直接拿到session对象,后面的自己处理。
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
建议查看,该篇博文Mybatis那些事-拦截器(Plugin+Interceptor
,理解拦截器的原理,我相信楼主,会知道在哪里处理用户信息的。
不知道是不是可以使用AOP进行拦截处理。
新建个ThreadLocal对象,每次掉dao前把用户信息存到threadlocal里面
在从你这个拦截器里面取用户信息就好。
如果不想侵入业务代码的话,dao层也可以搞个拦截器做把存储用户信息到threadlocal里面。