AOP 切面日志详细
1. 引入 spring-aspects
<!-- pom.xml 追加 -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.3.37</version>
</dependency>
mvn clean compile
确保没冲突。
2. 自定义注解
package com.lib.annotation;import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {String description() default ""; // 可选业务描述
}
3. 编写切面类
package com.lib.aspect;@Aspect
@Component
public class LoggingAspect {// 1. 定义切点:所有带 @LogExecution 的方法@Pointcut("@annotation(logAnnotation)")public void logPointcut(LogExecution logAnnotation) {}// 2. 环绕通知@Around("logPointcut(logAnnotation)")public Object logAround(ProceedingJoinPoint pjp,LogExecution logAnnotation) throws Throwable {long start = System.nanoTime();String className = pjp.getTarget().getClass().getSimpleName();String methodName = pjp.getSignature().getName();try {Object result = pjp.proceed(); // 继续执行原方法long cost = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);System.out.printf("[AOP-LOG] %s.%s | desc=%s | cost=%d ms | status=SUCCESS%n",className, methodName, logAnnotation.description(), cost);return result;} catch (Exception ex) {long cost = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);System.out.printf("[AOP-LOG] %s.%s | desc=%s | cost=%d ms | status=ERROR | msg=%s%n",className, methodName, logAnnotation.description(), cost, ex.getMessage());throw ex; // 继续抛出}}
}