close

本篇旨在讓讀者對Spring AOP實現原理有一個宏觀上的認識,因此會丟失一些細節,閱讀本篇文章前,希望讀者對Spring Ioc以及Spring AOP的使用(@Aspect)由一定了解,話不多說,直接上圖!
準備工作
在service bean的創建過程中(也就是getBean("service")),AOP通過BeanPostProcess後置處理器操作進行介入 分為2種情況:

所有的重點都在wrapIfNecessary做了什麼操作

創建完代理,代理如果調用方法呢?我們以Jdk動態代理為例子,方法的調用將會觸發invoke方法。

從上面可以看出,Spring AOP的代理invoke方法,其實是攔截器的執行。
我們先了解一下Spring AOP的執行順序,跟棧很像,後進先出

那麼這個攔截器鏈又如何保證before在after之前呢?而且還能保證find方法的執行順序?
這部分實現原理通過幾句話是解釋不完的,只能給出圖大家了解個大概

具體攔截器源碼:
publicclassMethodBeforeAdviceInterceptorimplementsMethodInterceptor,BeforeAdvice,Serializable{privatefinalMethodBeforeAdviceadvice;@OverridepublicObjectinvoke(MethodInvocationmi)throwsThrowable{//先調用before方法this.advice.before(mi.getMethod(),mi.getArguments(),mi.getThis());//繼續鏈式調用returnmi.proceed();}}publicclassAfterReturningAdviceInterceptorimplementsMethodInterceptor,AfterAdvice,Serializable{privatefinalAfterReturningAdviceadvice;@OverridepublicObjectinvoke(MethodInvocationmi)throwsThrowable{//先進行鏈式調用ObjectretVal=mi.proceed();//再調用afterReturning方法this.advice.afterReturning(retVal,mi.getMethod(),mi.getArguments(),mi.getThis());returnretVal;}}壓軸題:Spring AOP遇上循環依賴該部分難度係數十顆星,算是Spring源碼最複雜的一塊,這塊弄懂可以說對Spring的理解已經達到阿里水準了。這裡三言兩語是不可能解釋清楚的,只能貼個圖,大家有個宏觀上的認知。

Spring AOP是Spring重要的組成部分之一,本篇只是給讀者宏觀上的一個認識,具體還是需要閱讀源碼。
來源:bugpool.blog.csdn.net/article/details/105352273
END
關注後端面試那些事,回復【2022面經】
獲取最新大廠Java面經


全站熱搜