查了好多文章,这个最简单!!!!
package com.yc.meet.admin.aop;
import com.yc.meet.admin.dao.SysLogDao;
import com.yc.meet.admin.entity.SysLogEntity;
import com.yc.meet.admin.security.AuthUser;
import com.yc.meet.admin.utils.SecurityUtils;
import com.yc.meet.admin.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.jdbc.PreparedStatementLogger;
import org.apache.ibatis.logging.jdbc.StatementLogger;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;
import java.lang.reflect.Proxy;
import java.sql.Statement;
@Intercepts({
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class})
})
@Component
@Slf4j
public class SqlInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object result=invocation.proceed();
//获取sql
try{
String sql="";
Statement statement=(Statement) invocation.getArgs()[0];
if(Proxy.isProxyClass(statement.getClass())){
MetaObject metaObject= SystemMetaObject.forObject(statement);
Object h=metaObject.getValue("h");
if(h instanceof StatementLogger){
RoutingStatementHandler rsh=(RoutingStatementHandler) invocation.getTarget();
sql=rsh.getBoundSql().getSql();
}else {
PreparedStatementLogger psl=(PreparedStatementLogger) h;
sql=psl.getPreparedStatement().toString();
}
}else{
sql=statement.toString();
}
//插入日志,过滤掉日志本身的log
if(!sql.contains("sys_log")){
SysLogEntity sysLogEntity=new SysLogEntity();
AuthUser authUser= SecurityUtils.getUser();
if(authUser!=null){
sysLogEntity.setUserName(authUser.getUserName());
}
int index=sql.indexOf(":");
int length=sql.length();
String sqlString=sql.substring(index,length);
sysLogEntity.setSqlPhrase(sqlString);
Long date=System.currentTimeMillis();
sysLogEntity.setTime(date);
//拦截器中只能用这种方式来获取到类,自动注入注入不进来
SysLogDao sysLogDao= SpringUtil.getBean(SysLogDao.class);
sysLogDao.insert(sysLogEntity);
}
log.info("sql==================="+sql);
}catch (Exception e){
log.error("日志插入失败");
e.printStackTrace();
}
return result;
}
}
直接复制就可以啦,插入日志的实体和dao层自己写就行
可以是myabtis也可以是mybatisplus.无需自己拼接sql,也无需自己组装参数!!
执行后数据库中是这个样子,是一个完整的sql语句。我们的项目只用拦截除了查询以外的语句,所以我只拦截了update方法



