AOP配合注解的使用

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配合注解的使用

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值