美文网首页Java
Java注解记录method调用时间

Java注解记录method调用时间

作者: 西安法律咨询服务平台与程序员 | 来源:发表于2020-04-27 13:23 被阅读0次

1 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2 TimeConsume注解

package com.mervyn.filterdemo.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeConsume {
}

3 TimeConsume注解对应的TimeConsumeAspect

package com.mervyn.filterdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
public class TimeConsumeAspect {
    @Around("@annotation(timeConsume)")
    public Object computeTimeConsume(ProceedingJoinPoint proceedingJoinPoint, TimeConsume timeConsume) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        Signature signature = proceedingJoinPoint.getSignature();
        Class<?> targetClass = proceedingJoinPoint.getTarget().getClass();
        log.info("{}的{}方法耗时:{} milliseconds", targetClass.getName(), signature.getName(), (endTime - startTime));
        return result;
    }
}

4 使用TimeConsume注解

package com.mervyn.filterdemo.controller;

import com.mervyn.filterdemo.config.TimeConsume;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class FilterDemoController {
    @TimeConsume
    @GetMapping("hello")
    public String hello(){
        return "hello";
    }
}

5 效果

访问http://localhost/hello

com.mervyn.filterdemo.controller.FilterDemoController的hello方法耗时:8 milliseconds

相关文章

网友评论

    本文标题:Java注解记录method调用时间

    本文链接:https://www.haomeiwen.com/subject/lrydwhtx.html