StopWatch和切面优雅地结合起来的过程中,可以通过以下步骤实现Controller层和Service层之间的传递
public class StopWatchUtil {
private static final ThreadLocal<StopWatch> WATCHES = new ThreadLocal<>();
public static void start() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
WATCHES.set(stopWatch);
}
public static void stopAndLog(String methodName) {
StopWatch stopWatch = WATCHES.get();
stopWatch.stop();
System.out.println("Method: " + methodName + ", Execution Time: " + stopWatch.getTotalTimeMillis() + "ms");
WATCHES.remove();
}
}
@Aspect
@Component
public class TimingAspect {
@Pointcut("execution(* com.example.controller.*.*(..))")
private void controllerMethods() {}
@Pointcut("execution(* com.example.service.*.*(..))")
private void serviceMethods() {}
@Before("controllerMethods()")
public void beforeControllerMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
StopWatchUtil.start();
}
@After("controllerMethods()")
public void afterControllerMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
StopWatchUtil.stopAndLog(methodName);
}
@Before("serviceMethods()")
public void beforeServiceMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
StopWatchUtil.start();
}
@After("serviceMethods()")
public void afterServiceMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
StopWatchUtil.stopAndLog(methodName);
}
}
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/example")
public String exampleControllerMethod() {
return "Result";
}
}