【Spring實戰】—— 9 AOP環繞通知
假如有這么一個場景,需要統計某個方法執行的時間,如何做呢?
典型的會想到在方法執行前記錄時間,方法執行后再次記錄,得出運行的時間。
如果采用Spring的AOP,僅僅使用前置和后置方法是無法做到的,因為他們無法共享變量。這樣通過環繞通知,就可以快捷的實現。
首先在切面通知類中聲明環繞通知類:
public void watchPerformance(ProceedingJoinPoint joinpoint){ try{ System.out.println("begin!"); long start = System.currentTimeMillis(); joinpoint.proceed(); long end = System.currentTimeMillis(); System.out.println("end! performance took "+(end-start)+" milliseconds"); }catch(Throwable e){ System.out.println("eee!We want our money back!"); } }
在bean.xml配置文件中配置aop:around,鎖定方法:
<aop:around pointcut-ref="performance" method="watchPerformance"/>
這樣執行的結果如下:
The audience is taking their seats. The audience is turning off their cellphones begin! Instrumentalist age:25 Playing Jingle Bells:TOOT TOOT TOOT CLAP CLAP CLAP end! performance took 95 milliseconds
因此可以看出AOP執行的過程如下:
before() around() 執行方法() after/throw() around()