首先定義一個注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CostTime {
String value() default "";
}
然后定義一個切面處理類
@Aspect
@Component
public class CostTimeAOP {
final static Logger log = LoggerFactory.getLogger(CostTimeAOP.class);
@Pointcut("@annotation(cn.jesseyang.annotation.CostTime)")
public void costTimePointCut(){}
@Around("costTimePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//執(zhí)行方法
Object result = point.proceed();
//執(zhí)行時長(毫秒)
long time = System.currentTimeMillis() - beginTime;
logCostTime(point, time);
return result;
}
private void logCostTime(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
log.info("class:"+className+" method:"+methodName + " cost:"+time+"ms");
}
}