使用SpringAOP统计运行时间

本文介绍如何使用自定义注解和AOP切面在Java中统计方法的运行时间,通过三步实现:自定义注解、定义AOP切面、在目标方法上添加注解。此方案支持通过配置项开关控制,便于调试和性能优化。

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

实现步骤只需要3步:

1.自定义注解

2.定义一个AOP切面

3.在需要统计时间的方法上,添加注解。

 

自定义一个注解。使用value来定义方法的名称,方便读日志。定义一个阈值,运行时间超过阈值,才会记录下来。

/**
 * 统计方法运行的时间,单位毫秒
 * @see CountTimeAop
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CountTime {
    /**
     * 在日志中打印的名称
     * @return
     */
    String value() default "";

    /**
     * 运行时间超过该值,才会打印
     * @return 时间阈值
     */
    long thresholdMS() default 0;
}

定义切面。可以通过配置项count.time.debug.switch=1/0来打开或关掉时间统计功能

@Aspect
@Component
@ConditionalOnProperty(value = "count.time.debug.switch", havingValue = "1")
public class CountTimeAop {

    @Around("@annotation(countTime)")
    public Object around(ProceedingJoinPoint joinPoint, CountTime countTime) throws Throwable{
        long b = System.currentTimeMillis();
        try{
            return joinPoint.proceed();
        }finally {
            long e = System.currentTimeMillis();
            long time = e-b;
            if(time>countTime.thresholdMS())
                System.out.println(countTime.value()+" 花费时长(ms):"+(e-b));
        }
    }
}

在需要的bean方法上,添加对应的注解即可

效果:

很方便,不需要我们再去重复写统计时间了。打开关闭也可以通过配置文件来控制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值