【Spring實戰】—— 9 AOP環繞通知

假若有這麼一個場景,須要統計某個方法執行的時間,如何作呢?spa

  典型的會想到在方法執行前記錄時間,方法執行後再次記錄,得出運行的時間。code

 

若是採用Spring的AOP,僅僅使用前置和後置方法是沒法作到的,由於他們沒法共享變量。這樣經過環繞通知,就能夠快捷的實現。orm

  首先在切面通知類中聲明環繞通知類:xml

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,鎖定方法:blog

<aop:around pointcut-ref="performance" method="watchPerformance"/>

  這樣執行的結果以下:form

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執行的過程以下:class

  before()   around()   執行方法()   after/throw()   around()
相關文章
相關標籤/搜索