AOP配合注解实现日志打印
# Demo.class
/**
* demo接口类
*
* @author xiaoye
*/
@RestController
public class DemoController {
@LogAnnotation(name= "testName", type = "testType")
@GetMapping("test")
public String test() throws InterruptedException {
Thread.sleep(3000);
return "hello world";
}
}
# LogAnnotation.interface
/**
* 日志注解
*
* @author xiaoye
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String name() default "";
String type() default "";
}
# LogAspect.class
/**
* 日志织入
*
* @author xiaoye
*/
@Log4j2
@Component
@Aspect
public class LogAspect {
/**
* 配置切入点(伪目标方法)
*
*/
@Pointcut("@annotation(com.ls.annotation.LogAnnotation)")
public void point() {}
/**
* 环绕通知
*
* @param joinPoint 切入点
* @return String 目标方法返回值
* @throws Throwable invoke异常
*/
@Around("point()")
public Object aroundPoint(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
// 获取目标方法
Method method = signature.getMethod();
// 获取注解信息
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
// 目标类名
String className = joinPoint.getTarget().getClass().getName();
// 目标方法名
String methodName = signature.getName();
// 注解name
String name = annotation.name();
// 注解type
String type = annotation.type();
long startTime = System.currentTimeMillis();
// 目标方法执行
Object proceed = joinPoint.proceed();
long endTime = System.currentTimeMillis();
// 打印日志
log.info("class: {}", className);
log.info("methodName: {}", methodName);
log.info("AnnotationName: {}", name);
log.info("AnnotationType: {}", type);
log.info("总耗时:{} ms", endTime - startTime);
// 返回值处理
return proceed;
}
}
结果展示

本文介绍了如何利用AOP(面向切面编程)配合LogAnnotation注解,在Spring Boot应用中实现细粒度的方法级日志打印,包括日志的名称、类型以及方法执行的时间统计。
1248

被折叠的 条评论
为什么被折叠?



