- 自定义注解类
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
- 定义切面类
pom引入aop:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
切面类:
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
@Pointcut("@annotation(com.lu.springbootdemo.annotation.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
saveLog(point, time);
return result;
}
private void saveLog(ProceedingJoinPoint point, long time) {
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
SysLog sysLog = method.getAnnotation(SysLog.class);
SysLogEntity sysLogEntity = new SysLogEntity();
if (null != sysLog) {
sysLogEntity.setOperation(sysLog.value());
}
sysLogEntity.setMethod(point.getTarget().getClass().getName() + "." + method.getName() + "()");
sysLogEntity.setParams(JSON.toJSONString(point.getArgs()));
sysLogEntity.setTime(time);
sysLogService.save(sysLogEntity);
}
}
注解使用:
@SysLog("查看用户列表")
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<UserEntity> users() {
return userService.users();
}