javascript
正确理解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;@Aspectpublic 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 advicereturn retVal;}}?
?
?
現在大家看明白了吧,并不是在joinpoint執行前后各調用一次pointcut,而是在pointcut中把joinpoint給around起來。
?
摘自:http://blog.163.com/chen_guangqi/blog/static/2003111492012101653052508/
轉載于:https://www.cnblogs.com/csniper/p/5499248.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的正确理解Spring AOP中的Around advice的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring注意事项(各部分理解)
- 下一篇: 2016省赛总结