自定义注解--测试方法消耗的时间

本文介绍如何创建自定义注解,用于跟踪并测量测试方法的执行时间,提升测试效率和代码性能分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

切面类:

package com.taikang.pension.mall.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: itw_subd
 * @Date: 2019/12/16 15:51
 * @Description: 测试方法请求时间的切面类
 */
@Aspect
@Component
@Slf4j
public class RequestTimeTestAspect {
    Long startTime = 0L;
    Long endTime = 0L;
    Long costTime = 0L;

    @Pointcut("@annotation(com.taikang.pension.mall.annotation.RequestTime)")
    public void requestTime() {
    }

    ;

    @Before(value = "requestTime()")
    public void before() {
        startTime = System.currentTimeMillis();
    }

    @After(value = "requestTime()")
    public void after(JoinPoint joinPoint) {
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            endTime = System.currentTimeMillis();
            costTime = endTime - startTime;
            StringBuilder stringBuilder = new StringBuilder(method.getName());
            stringBuilder.append("执行时间花费了").append(costTime);
            log.info(stringBuilder.toString());
        } catch (Exception e) {
            log.error("requestTime after 报错了,但是不能影响方法执行.");
        }

    }
}

注解类:

package com.taikang.pension.mall.annotation;

import java.lang.annotation.*;

/**
 * @Author: itw_subd
 * @Date: 2019/12/16 16:05
 * @Description: 测试请求时间 注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestTime {
    String name() default "";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值