spring aop環繞通知


【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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM