正确理解Spring AOP中的Around advice
Spring AOP中,有Before advice和After advice,這兩個advice從字面上就可以很容易理解,但是Around advice就有點麻煩了。
乍一看好像是Before advice和After advice的組合,也就是說pointcut會在joinpoint執(zhí)行前后各執(zhí)行一次。但是這種理解是不正確的,如果這樣理解的話,就會產(chǎn)生這樣的疑問:spring aop Around類型為什么只執(zhí)行一次?,這個帖子是我碰巧看到。
那么怎么樣理解才是正確的呢?我們來看一下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執(zhí)行前后做一些事情的機會,可以決定什么時候,怎么樣去執(zhí)行joinpoint,甚至可以決定是否真的執(zhí)行joinpoint的方法調(diào)用。Around advice通常是用在下面這樣的情況:
在多線程環(huán)境下,在joinpoint方法調(diào)用前后的處理中需要共享一些數(shù)據(jù)。如果使用Before advice和After advice也可以達到目的,但是就需要在aspect里面創(chuàng)建一個存儲共享信息的field,而且這種做法并不是線程安全的。
現(xiàn)在,明白Spring設(shè)計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 相當(dāng)于是before advice Object retVal = pjp.proceed();// stop stopwatch 相當(dāng)于是after advicereturn retVal;}}?
?
?
現(xiàn)在大家看明白了吧,并不是在joinpoint執(zhí)行前后各調(diào)用一次pointcut,而是在pointcut中把joinpoint給around起來。
?
摘自:http://blog.163.com/chen_guangqi/blog/static/2003111492012101653052508/
轉(zhuǎn)載于:https://www.cnblogs.com/csniper/p/5499248.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的正确理解Spring AOP中的Around advice的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring注意事项(各部分理解)
- 下一篇: 5月16 JSON的一些知识点及AJAX