上篇文章说到使用原生的StopWatch查看程序执行时间,本文将介绍使用注解+AOP(面向切面编程)的方式实现其功能,一来能够快速使用StopWatch功能,二来让你们熟悉一下如何使用注解进行切面编程spring
@Retention(RetentionPolicy.RUNTIME) @Target({METHOD}) public @interface StopWatchTime { String value() default ""; }
本注解主要用在方法上,故target为METHOD,并设定一个value,可用于定义这次观察的名称。编程
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@Aspect // 1 @Component // 2 public class StopWatchTimeAdvice { @Around("@annotation(stopWatchTime)") // 3 public Object invoke(ProceedingJoinPoint thisJoinPoint, StopWatchTime stopWatchTime) throws Throwable { MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature(); String name = StringUtils.isEmpty(stopWatchTime.value()) ? methodSignature.getName() : stopWatchTime.value(); // 4 StopWatch stopWatch = new StopWatch(name); stopWatch.start("00"); Object object = thisJoinPoint.proceed(); // 5 stopWatch.stop(); System.err.println(stopWatch.prettyPrint()); // 6 return object; } }
代码解释spring-boot
@StopWatchTime public void run(String... strings) throws Exception { step1(); step2(); step3(); } private void step1() throws InterruptedException { Thread.sleep(100L); } private void step2() throws InterruptedException { Thread.sleep(850L); } private void step3() throws InterruptedException { Thread.sleep(2000L); }
只要@StopWatchTime写在哪一个方法上就能监控得出哪一个方法的执行时间,但且限于public非静态方法this
<pre> StopWatch 'run': running time (millis) = 2985 ----------------------------------------- ms % Task name ----------------------------------------- 02985 100% 00 </pre>.net
你们可能会看出来,此方法虽然使用起来方便,但只能显示单个方法的执行时间,下一篇将告诉你们如何使用AOP的方法扩展出可同时观察一个代码段里多个方法的执行状况,敬请期待。code