第一步:自定义一个注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoLog {
String operateType() default "";
}
第二步:写切面类
@Slf4j
@Component
@Aspect
public class AutoLogAspect {
@Pointcut("@annotation(io.swagger.v3.oas.annotations.Operation)")
public void controllerLog() {
throw new UnsupportedOperationException();
}
@Around("controllerLog()")
public Object handleAround(ProceedingJoinPoint point) throws Throwable {
//获取当前的时间戳
long s = System.currentTimeMillis();
//获取当前请求对象,记录请求信息
Object[] args = point.getArgs();
Object result = point.proceed();
//获得切点的方法
Method method = ((MethodSignature) point.getSignature()).getMethod();
AutoLog annotation = method.getAnnotation(AutoLog.class);
log.info("用户操作类型: {}", annotation.operateType());
log.info("请求方法 : 【{}】", method);
log.info("请求参数 : {}", args);
log.info("返回结果 : {}", Objects.isNull(result) ? "" : result);
log.info("方法执行总耗时 : {} ms", System.currentTimeMillis() - s);
return result;
}
}
第三步:注解解释
-
@Slf4j:日志注解
@Component:定义Spring管理Bean(也就是将标注@Component注解的类交由spring管理)
@Aspect:切面类表示 (啊死帕克特)
@Pointcut:切入点 (喷卡特)
ProceedingJoinPoint类:Proceedingjoinpoint
继承了JoinPoint,在JoinPoint的基础上暴露出 proceed(), 这个方法是AOP代理链执行的方法。可以获取请求方法,参数,返回结构的值
@Before :前置通知
@AfterReturning :配置后置通知,在切入点方法正常执行后执行
@AfterThrowing:配置异常通知
@After:后置通知
@Around:环绕通知
第四步:使用
在需要的类上加入@AutoLog注解即可
@RestController
@RequestMapping(value = "/user")
//@ResponseResultBody 这个也是一种统一返回,需要加注解,暂时不用,用第二种
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@Operation(summary = "查询所有用户", description = "查询所有数据,开发:hxs")
@GetMapping(value = "/select")
//此注解生效切面
@AutoLog(operateType = "")
public List<UserDTO> select() {
return userService.select();
}
}
这样就是一个完整的SpringAop的实现方式
自定义注解,详情请看专栏中自定义注解如何实现