Spring Aop基本流程原理示例詳解
一、代理對象的創(chuàng)建過程:
AbstractAutowireCapableBeanFactory#initializeBean
protectedObjectinitializeBean(StringbeanName,Objectbean,@NullableRootBeanDefinitionmbd){ if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{ invokeAwareMethods(beanName,bean); return null;},getAccessControlContext()); } else{invokeAwareMethods(beanName,bean); } ObjectwrappedBean=bean; if(mbd==null||!mbd.isSynthetic()){// 執(zhí)⾏所有的BeanPostProcessor#postProcessBeforeInitialization 初始化之前的處理器⽅法wrappedBean=applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName); } try{// 這⾥就開始執(zhí)⾏afterPropertiesSet(實現(xiàn)了InitializingBean接⼝)⽅法和initMethodinvokeInitMethods(beanName,wrappedBean,mbd); } catch(Throwableex){thrownewBeanCreationException((mbd!=null? mbd.getResourceDescription():null),beanName,'Invocationofinitmethodfailed',ex); } if(mbd==null||!mbd.isSynthetic()){// 整個Bean初始化完成,執(zhí)⾏后置處理器⽅法wrappedBean=applyBeanPostProcessorsAfterInitialization(wrappedBean,beanName); } return wrappedBean;}
可以看到有初始化前執(zhí)行的方法、初始化時執(zhí)行的方法、初始化之后執(zhí)行的方法,我們從初始化之后執(zhí)行的方法入手。
二、applyBeanPostProcessorsAfterInitialization
applyBeanPostProcessorsAfterInitialization()方法的流程如下:
AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization->AbstractAutoProxyCreator#postProcessAfterInitialization
applyBeanPostProcessorsAfterInitialization中會檢查下該類是否已經(jīng)暴露過了(可能已經(jīng)創(chuàng)建了,⽐如A依賴B時,創(chuàng)建A時候,就會先去創(chuàng)建B。當(dāng)真正需要創(chuàng)建B時,就沒必要再代理⼀次已經(jīng)代理過的對象),避免重復(fù)創(chuàng)建。
->AbstractAutoProxyCreator#wrapIfNecessary
得到所有候選Advisor,對Advisors和bean的⽅法雙層遍歷匹配,最終得到⼀個List<Advisor>,即specificInterceptors
->AbstractAutoProxyCreator#createProxy
(1)創(chuàng)建代理的⼯作交給ProxyFactory
(2)把指定和通⽤攔截對象合并, 并都適配成Advisor
(3)上⾯準(zhǔn)備做完就開始創(chuàng)建代理
->proxyFactory.getProxy()
⽤ProxyFactory創(chuàng)建AopProxy, 然后⽤AopProxy創(chuàng)建Proxy, 所以這⾥重要的是看獲取的AopProxy對象是什么,然后進去看怎么創(chuàng)建動態(tài)代理, 提供了兩種:jdk proxy, cglib
總結(jié):簡要流程
總結(jié)
到此這篇關(guān)于Spring Aop基本流程原理的文章就介紹到這了,更多相關(guān)Spring Aop流程原理內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
