切面类:
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 "";
}