正確理解Spring AOP中的Around advice


Spring AOP中,有Before advice和After advice,這兩個advice從字面上就可以很容易理解,但是Around advice就有點麻煩了。

乍一看好像是Before advice和After advice的組合,也就是說pointcut會在joinpoint執行前后各執行一次。但是這種理解是不正確的,如果這樣理解的話,就會產生這樣的疑問:spring aop Around類型為什么只執行一次 ,這個帖子是我碰巧看到。

那么怎么樣理解才是正確的呢?我們來看一下Spring官方是怎么解釋Around advice的:

Around advice runs "around" a matched method execution. It has the opportunity to do work both before and after the method executes, and to determine when, how, and even if, the method actually gets to execute at all. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer for example).

大概的意思就是說,Around advice可以通過一個在joinpoint執行前后做一些事情的機會,可以決定什么時候,怎么樣去執行joinpoint,甚至可以決定是否真的執行joinpoint的方法調用。Around advice通常是用在下面這樣的情況:

在多線程環境下,在joinpoint方法調用前后的處理中需要共享一些數據。如果使用Before advice和After advice也可以達到目的,但是就需要在aspect里面創建一個存儲共享信息的field,而且這種做法並不是線程安全的。

現在,明白Spring設計Around advice的目的之后,我們來看下具體的用法。

 

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.ProceedingJoinPoint;

 

@Aspect

public class AroundExample {

  @Around("com.xyz.myapp.SystemArchitecture.businessService()")

  public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {

    // start stopwatch   相當於是before advice

    Object retVal = pjp.proceed();

    // stop stopwatch    相當於是after advice

    return retVal;

  }

}

 

 

 

現在大家看明白了吧,並不是在joinpoint執行前后各調用一次pointcut,而是在pointcut中把joinpoint給around起來。

 

摘自:http://blog.163.com/chen_guangqi/blog/static/2003111492012101653052508/


免責聲明!

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



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