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;
}
}
结果展示