代码如下:
@Aspect
@Slf4j
@Component
public class PerformanceAspect {
// 用于统计一个方法的执行时间和结果(成功执行、执行出错)
@Around("repositoryOps()")
public Object logPerformance(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
String methodName = "-";
String result = "Y";
try {
methodName = pjp.getSignature().toShortString();
return pjp.proceed();
} catch (Throwable t) {
result = "N";
throw t;
} finally {
long end = System.currentTimeMillis();
log.info("{};{};{}ms", methodName, result, (end - start));
}
}
// cn.wu.service 包下的任意类的任意方法
@Pointcut("execution(* cn.wu.service.*.*(..))")
private void repositoryOps() {
}
}
结果如下:
cn.wu.aspect.PerformanceAspect : UserService.findAll();Y;655ms