需求
在项目中有需要对表数据进行增删改的操作,都新增一条日志到日志表(字段:id、操作人、操作时间、操作类名、操作方法名、操作参数列表、操作运行时长)中
因为只对增删改操作添加日志,而查的操作不需要,所以使用注解的形式去实现更方便,如果使用execution表达式相对麻烦
自定义注解
java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//设置在方法上生效
@Target(ElementType.METHOD)
//设置运行时生效
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
}
放置自定义注解
在service impl 中对应的增删改方法上,放置@MyLog注解
ascept
java
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class LogAspect {
//拿到日志类的mapper接口,用于新增日志数据
@Autowired
private OperateLogMapper mapper;
//用于获取token
@Autowired
private HttpServletRequest request;
//可以使用全限定名,也可以直接使用注解名
// @Around("@annotation(cn.emp.aspect.MyLog)")
@Around("@annotation(MyLog)")
public Object sysLog(ProceedingJoinPoint point) throws Throwable {
//实例化日志类对象
OperateLog operateLog = new OperateLog();
//获取token ,用于查询当前操作的用户名
String token = request.getHeader("token");
//将查询的token通过jwt工具类进行解析,在返回的解析内容中获取用户名
operateLog.setOperator(JWTUtils.parseJwt(token).get("username").toString());
//拿到目标对象,getname,获取当前操作的类名
operateLog.setClassName(point.getTarget().getClass().getName());
//获取当前操作的方法名
operateLog.setMethodName(point.getSignature().getName());
//获取方法参数列表
operateLog.setMethodParam(Arrays.toString(point.getArgs()));
//获取操作前系统时间,使用毫秒数
long startTime = System.currentTimeMillis();
//执行方法
Object proceed = point.proceed();
//获取操作后当前时间
long endTime = System.currentTimeMillis();
//将时间相减,得到方法执行时长
operateLog.setCostTime(endTime-startTime);
//将数据写入日志
mapper.insertLog(operateLog);
return proceed;
}
}
上述代码中涉及到的jwt工具类->Java springboot实现JWT登录-附源码