说明:可自动打印方法运行时间。
    使用:在方法上添加@RunningTime注解。可以直接通过value属性添加方法注解,或者添加Swagger 的ApiOperation注解,说明方法用途。都为空时,使用全限定方法名。
    image.png
    结果:image.png

    注解:@RunningTime

    1. import java.lang.annotation.ElementType;
    2. import java.lang.annotation.Retention;
    3. import java.lang.annotation.RetentionPolicy;
    4. import java.lang.annotation.Target;
    5. /**
    6. * 记录方法运行毫秒数
    7. * @author chajiu
    8. */
    9. @Target(ElementType.METHOD)
    10. @Retention(RetentionPolicy.RUNTIME)
    11. public @interface RunningTime {
    12. /**
    13. * 方法注解,为空时搜索ApiOperation的注解,都为空时,使用全限定方法名
    14. * @return
    15. */
    16. String value() default "";
    17. }

    切面:

    1. import co.yixiang.modules.system.aspect.aop.RunningTime;
    2. import io.swagger.annotations.ApiOperation;
    3. import lombok.extern.slf4j.Slf4j;
    4. import org.aspectj.lang.ProceedingJoinPoint;
    5. import org.aspectj.lang.annotation.Around;
    6. import org.aspectj.lang.annotation.Aspect;
    7. import org.aspectj.lang.annotation.Pointcut;
    8. import org.aspectj.lang.reflect.MethodSignature;
    9. import org.springframework.stereotype.Component;
    10. import java.lang.reflect.Method;
    11. @Component
    12. @Aspect
    13. @Slf4j
    14. public class MethodRunningLogAspect {
    15. ThreadLocal<Long> currentTime = new ThreadLocal<>();
    16. @Pointcut("@annotation(co.yixiang.modules.system.aspect.aop.RunningTime)")
    17. public void thisPointCut(){
    18. }
    19. @Around("thisPointCut()")
    20. public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    21. currentTime.set(System.currentTimeMillis());
    22. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    23. Method method = signature.getMethod();
    24. ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
    25. RunningTime runningTime = method.getAnnotation(RunningTime.class);
    26. Object res = joinPoint.proceed();
    27. String methodNote = "";
    28. boolean flag=false;
    29. if(!"".equals(runningTime.value())){
    30. methodNote = runningTime.value();
    31. flag = true;
    32. }
    33. if(!flag && apiOperation !=null){
    34. methodNote = apiOperation.value();
    35. }
    36. if("".equals(methodNote)){
    37. methodNote = joinPoint.getTarget().getClass().getName() + "."+method.getName();
    38. }
    39. log.info("耗时:"+methodNote +" {}毫秒",System.currentTimeMillis() - currentTime.get());
    40. return res;
    41. }
    42. }