Java Aspect 记录程序运行时碰到的问题。具体见代码。
测试说明
在TestComponent中有task1和task2两个方法,都用了TaskMonitor注解。其中task1中调用了task2的方法,在controller测试勒中调用了task1方法。预期的结果是task1和task2都会记录运行时间,但是测试结果只记录了task1的运行时间。想请问这是为什么,也想知道如何修改才能同时输出task1和task2的运行时间。ps:将task1和task2放在不同的bean中,然后通过bean调用确实可以同时输出task1和task2的记录时间,但是我不想这么做。求其他解决方案。
具体代码
注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TaskMonitor {
String taskName() default "";
}
Aspect类
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Component
@Order(-1)
@Slf4j
public class TaskMonitorAspect {
@Pointcut("execution(@com.TaskMonitor * *(..))")
private void timeMonitor() {}
@Around("timeMonitor()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
TaskMonitor monitor = method.getAnnotation(TaskMonitor.class);
String splitLine = "=========================";
log.info(String.format("%s开始执行任务%s%s: ", splitLine, monitor.taskName(), splitLine));
Object result = joinPoint.proceed(joinPoint.getArgs());
stopWatch.stop();
log.info(String.format("运行时间: %sms",stopWatch.getTotalTimeMillis()));
log.info(String.format("%s%s任务执行结束%s: ", splitLine, monitor.taskName(), splitLine));
return result;
} catch (Throwable e) {
throw e;
}
}
}
测试类
@Component
public class TestComponent {
@Autowired TestComponent2 testComponent2;
@TaskMonitor(taskName = "任务1")
public void task1() {
try {
Thread.sleep(500);
this.task2();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@TaskMonitor(taskName = "任务2")
public void task2() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@RestController
public class TestController {
@Autowired TestComponent testComponent;
@GetMapping("/test")
public String test(){
testComponent.task1();
return "SUCCESS";
}
}