自定义注解计算方法耗时

本文介绍了如何在Spring Boot项目中使用AOP实现自定义注解,并通过AspectJ监控带有@TimeConsuming注解的方法的时间消耗。步骤包括添加依赖、创建自定义注解、编写切面类和应用注解实例。

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

1、首先引入所需要依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.6.8</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.7</version>
</dependency>

2、自定义注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeConsuming {
    String value() default "";
}

3、实现切面

@Slf4j
@Aspect
@Component
public class TimeAspect {
    @Pointcut("@annotation(com.dada.jdk.aop.TimeConsuming)")
    private void timePoint() {
    }

    @Around("timePoint() && @annotation(timeConsuming)")
    public Object timePoint(ProceedingJoinPoint pjp, TimeConsuming timeConsuming) throws Throwable {
        Long startTime = System.currentTimeMillis();
        pjp.proceed();
        Long endTime = System.currentTimeMillis();
        log.info(timeConsuming.value());
        log.info("cost time is:{}", endTime - startTime);
        return pjp;
    }
}

4、使用注解

    @TimeConsuming("AopDemo")
    public void put(){
        System.out.println("this is a function");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值