javascript
nfvo通过调用哪个接口实现对vnf生命周期的管理_Spring-Bean生命周期
只有四個!只有四個!只有四個!
是的,Spring Bean的生命周期只有這四個階段。
要徹底搞清楚Spring的生命周期,首先要把這四個階段牢牢記住。實例化和屬性賦值對應(yīng)構(gòu)造方法和setter方法的注入,初始化和銷毀是用戶能自定義擴展的兩個階段。
實例化 -> 屬性賦值 -> 初始化 -> 銷毀
第一大類:影響多個Bean的接口
實現(xiàn)了這些接口的Bean會切入到多個Bean的生命周期中。正因為如此,這些接口的功能非常強大,Spring內(nèi)部擴展也經(jīng)常使用這些接口,例如自動注入以及AOP的實現(xiàn)都和他們有關(guān)。
- BeanPostProcessor
- InstantiationAwareBeanPostProcessor
這兩兄弟可能是Spring擴展中最重要的兩個接口!InstantiationAwareBeanPostProcessor作用于實例化階段的前后,BeanPostProcessor作用于初始化階段的前后。如圖:
其中 InstantiationAwareBeanPostProcessor繼承自BeanPostProcessor 是spring非常重要的拓展接口
BeanPostProcessor#postProcessAfterInitialization接口完成初始化。
2、postProcessAfterInstantiation調(diào)用時機為bean實例化(Instantiation)之后和任何初始化(Initialization)之前。
3、postProcessProperties調(diào)用時機為postProcessAfterInstantiation執(zhí)行之后并返回true, 返回的PropertyValues將作用于給定bean屬性賦值. spring 5.1之后出現(xiàn)以替換@Deprecated標注的postProcessPropertyValues
4、postProcessPropertyValues已經(jīng)被標注@Deprecated,后續(xù)將會被postProcessProperties取代。
進入執(zhí)行流程
步驟1 :InstantiationAwareBeanPostProcessor的觸發(fā)入口從AbstractAutowireCapableBeanFactory#createBean開始。
/*** Central method of this class: creates a bean instance,* populates the bean instance, applies post-processors, etc.** @see #doCreateBean*/ @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {// 省略......try {/*** 注釋1. InstantiationAwareBeanPostProcessor#postProcessorsBeforeInstantiation觸發(fā)入口*/Object bean = resolveBeforeInstantiation(beanName, mbdToUse);if (bean != null) {return bean;}} catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);}// 省略......try {/*** 注釋2. postProcessAfterInstantiation、postProcessProperties 觸發(fā)入口* 主要邏輯都在doCreateBean()方法中,* 方法中包含了實例化、屬性賦值、初始化過程。邏輯很清晰* 這三個方法與三個生命周期階段一一對應(yīng),非常重要*/Object beanInstance = doCreateBean(beanName, mbdToUse, args);if (logger.isTraceEnabled()) {logger.trace("Finished creating instance of bean '" + beanName + "'");}return beanInstance;} catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {// A previously detected exception with proper bean creation context already,// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.throw ex;} catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);} }步驟2:注釋1中,跟進AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation, 分析postProcessorsBeforeInstantiation執(zhí)行時機 :
/** 注釋1 代碼進入后執(zhí)行InstantiationAwareBeanPostProcessor#ostProcessBeforeInstantiation方法*/ @Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {Object bean = null;if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {// Make sure bean class is actually resolved at this point.if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {Class<?> targetType = determineTargetType(beanName, mbd);if (targetType != null) {/*** 注釋3:回調(diào)beanPostProcessorsBeforeInstantiation實例化,如果返回bean非null則直接執(zhí)行* 不為空null就直接返回了而不執(zhí)行doCreateBean()方法了,而該方法是創(chuàng)建Bean對象的方法* beanPostProcessorsAfterInitialization進行實例初始化*/bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);if (bean != null) {/** 注釋4 */bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);}}}mbd.beforeInstantiationResolved = (bean != null);}return bean; }/**注釋3 代碼跟進*/ @Nullable protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {/*** 注釋5:只要其中一個postProcessBeforeInstantiation返回實例bean即結(jié)束回調(diào),* 這個bean將會直接返回給bean容器管理*/InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);if (result != null) {return result;}}}return null; }/** 注釋4 代碼跟進*/ @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;for (BeanPostProcessor processor : getBeanPostProcessors()) {/**注釋6 */Object current = processor.postProcessAfterInitialization(result, beanName);if (current == null) {return result;}result = current;}return result; }可以看到,postProcessBeforeInstantiation在doCreateBean之前調(diào)用,也就是在bean實例化之前調(diào)用的,英文源碼注釋解釋道該方法的返回值會替換原本的Bean作為代理,這也是Aop等功能實現(xiàn)的關(guān)鍵點。
代碼說明:1. 注釋5中,如果postProcessBeforeInstantiation方法返回了Object是null;那么就直接返回,調(diào)用doCreateBean方法();
2. 注釋5中,如果postProcessBeforeInstantiation返回不為null;說明修改了bean對象;然后這個時候就立馬執(zhí)行postProcessAfterInitialization方法(注意這個是初始化之后的方法,也就是通過這個方法實例化了之后,直接執(zhí)行初始化之后的方法;中間的實例化之后 和 初始化之前都不執(zhí)行);
3. 注釋6中,在調(diào)用postProcessAfterInitialization方法時候如果返回null;那么就直接返回,調(diào)用doCreateBean方法();(初始化之后的方法返回了null,那就需要調(diào)用doCreateBean生成對象了)
4. 在調(diào)用postProcessAfterInitialization時返回不為null;那這個bean就直接返回給ioc容器了初始化之后的操作是這里面最后一個方法了;
步驟2:跟進AbstractAutowireCapableBeanFactory#doCreateBean, 分析postProcessAfterInstantiation、postProcessProperties執(zhí)行時機 :
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {/** 注釋7 實例化階段! */instanceWrapper = createBeanInstance(beanName, mbd, args);}// 省略......// Initialize the bean instance.Object exposedObject = bean;try {/** 注釋8 依據(jù)bean definition 完成bean屬性賦值 */populateBean(beanName, mbd, instanceWrapper);/** 注釋9 執(zhí)行bean初始化 */exposedObject = initializeBean(beanName, exposedObject, mbd);} catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;} else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}// 省略......return exposedObject; }這三個方法與三個生命周期階段一一對應(yīng),非常重要
注釋8中,繼續(xù)跟進AbstractAutowireCapableBeanFactory#populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the// state of the bean before properties are set. This can be used, for example,// to support styles of field injection.boolean continueWithPropertyPopulation = true;// InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()/*** 注釋10:滿足兩個要求:* 1、BeanDefinition為應(yīng)用程序bean,而非基礎(chǔ)框架bean信息。* 2、注冊過InstantiationAwareBeanPostProcessor類型接口,上文有提到這個標志位。* 3、注冊了多個接口時,只要其中一個postProcessAfterInstantiation返回false,即停止后續(xù)執(zhí)行。*/ if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {continueWithPropertyPopulation = false;break;}}}}// 忽略后續(xù)的屬性賦值操作代碼 }可以看到該方法在屬性賦值方法內(nèi),但是在真正執(zhí)行賦值操作之前。其返回值為boolean,返回false時可以阻斷屬性賦值階段(continueWithPropertyPopulation = false;)
關(guān)于BeanPostProcessor執(zhí)行階段的源碼穿插在下文Aware接口的調(diào)用時機分析中,因為部分Aware功能的就是通過他實現(xiàn)的!只需要先記住BeanPostProcessor在初始化前后調(diào)用就可以了。
第二大類:只調(diào)用一次的接口
這一大類接口的特點是功能豐富,常用于用戶自定義擴展。
第二大類中又可以分為兩類:
Aware類型的接口的作用就是讓我們能夠拿到Spring容器中的一些資源?;径寄軌蛞娒?#xff0c;Aware之前的名字就是可以拿到什么資源,例如BeanNameAware可以拿到BeanName,以此類推。調(diào)用時機需要注意:所有的Aware方法都是在初始化階段之前調(diào)用的!
Aware接口眾多,這里同樣通過分類的方式幫助大家記憶。
Aware接口具體可以分為兩組,至于為什么這么分,詳見下面的源碼分析。如下排列順序同樣也是Aware接口的執(zhí)行順序,能夠見名知意的接口不再解釋。
Aware Group1
Aware Group2
這里涉及到另一道面試題,ApplicationContext和BeanFactory的區(qū)別,可以從ApplicationContext繼承的這幾個接口入手,除去BeanFactory相關(guān)的兩個接口就是ApplicationContext獨有的功能,這里不詳細說明。
Aware調(diào)用時機源碼分析
詳情如下,忽略了部分無關(guān)代碼。代碼位置就是我們上文提到的initializeBean方法詳情,這也說明了Aware都是在初始化階段之前調(diào)用的!
// 注釋9 代碼進入 調(diào)用初始化階段 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {// 注釋11 這里調(diào)用的是Group1中的三個Bean開頭的AwareinvokeAwareMethods(beanName, bean);Object wrappedBean = bean;/** * 這里調(diào)用的是Group2中的幾個Aware,* 而實質(zhì)上這里就是前面所說的BeanPostProcessor的調(diào)用點!* 也就是說與Group1中的Aware不同,這里是通過BeanPostProcessor(ApplicationContextAwareProcessor)實現(xiàn)的。*//** 注釋12 */wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);/** 注釋13 下文即將介紹的InitializingBean調(diào)用點 */invokeInitMethods(beanName, wrappedBean, mbd);/** 注釋14 BeanPostProcessor的另一個調(diào)用點*/wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);return wrappedBean; }/**注釋11 代碼進入 */ private void invokeAwareMethods(final String beanName, final Object bean) {if (bean instanceof Aware) {if (bean instanceof BeanNameAware) {((BeanNameAware) bean).setBeanName(beanName);}if (bean instanceof BeanClassLoaderAware) {((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());}if (bean instanceof BeanFactoryAware) {((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);}} }注釋11 代碼進入后,可以看到并不是所有的Aware接口都使用同樣的方式調(diào)用。Bean××Aware都是在代碼中直接調(diào)用的。
而ApplicationContext相關(guān)的Aware都是通過applyBeanPostProcessorsBeforeInitialization來調(diào)用BeanPostProcessor#postProcessBeforeInitialization()實現(xiàn)的。感興趣的可以自己看一下ApplicationContextAwareProcessor這個類的源碼,就是判斷當(dāng)前創(chuàng)建的Bean是否實現(xiàn)了相關(guān)的Aware方法,如果實現(xiàn)了會調(diào)用回調(diào)方法將資源傳遞給Bean。
至于Spring為什么這么實現(xiàn),應(yīng)該沒什么特殊的考量。也許和Spring的版本升級有關(guān)。基于對修改關(guān)閉,對擴展開放的原則,Spring對一些新的Aware采用了擴展的方式添加。
BeanPostProcessor的調(diào)用時機也能在這里體現(xiàn),包圍住invokeInitMethods方法,也就說明了在初始化階段的前后執(zhí)行。
關(guān)于Aware接口的執(zhí)行順序,其實只需要記住第一組在第二組執(zhí)行之前就行了。每組中各個Aware方法的調(diào)用順序其實沒有必要記,有需要的時候點進源碼一看便知。簡單的兩個生命周期接口
至于剩下的兩個生命周期接口就很簡單了,實例化和屬性賦值都是Spring幫助我們做的,能夠自己實現(xiàn)的有初始化和銷毀兩個生命周期階段。
有一點需要注意,因為Aware方法都是執(zhí)行在初始化方法之前,所以可以在初始化方法中放心大膽的使用Aware接口獲取的資源,這也是我們自定義擴展Spring的常用方式。
除了實現(xiàn)InitializingBean接口之外還能通過注解或者xml配置的方式指定初始化方法,至于這幾種定義方式的調(diào)用順序其實沒有必要記。因為這幾個方法對應(yīng)的都是同一個生命周期,只是實現(xiàn)方式不同,我們一般只采用其中一種方式。
擴展閱讀: BeanPostProcessor 注冊時機與執(zhí)行順序
注冊時機
我們知道BeanPostProcessor也會注冊為Bean,那么Spring是如何保證BeanPostProcessor在我們的業(yè)務(wù)Bean之前初始化完成呢?
請看我們熟悉的refresh()方法的源碼,省略部分無關(guān)代碼:
可以看出,Spring是先執(zhí)行registerBeanPostProcessors()進行BeanPostProcessors的注冊,然后再執(zhí)行finishBeanFactoryInitialization初始化我們的單例非懶加載的Bean。
執(zhí)行順序
BeanPostProcessor有很多個,而且每個BeanPostProcessor都影響多個Bean,其執(zhí)行順序至關(guān)重要,必須能夠控制其執(zhí)行順序才行。關(guān)于執(zhí)行順序這里需要引入兩個排序相關(guān)的接口:PriorityOrdered、Ordered
- PriorityOrdered是一等公民,首先被執(zhí)行,PriorityOrdered公民之間通過接口返回值排序
- Ordered是二等公民,然后執(zhí)行,Ordered公民之間通過接口返回值排序
- 都沒有實現(xiàn)是三等公民,最后執(zhí)行
在以下源碼中,可以很清晰的看到Spring注冊各種類型BeanPostProcessor的邏輯,根據(jù)實現(xiàn)不同排序接口進行分組。優(yōu)先級高的先加入,優(yōu)先級低的后加入。
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. // 首先,加入實現(xiàn)了PriorityOrdered接口的BeanPostProcessors,順便根據(jù)PriorityOrdered排了序String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // 然后,加入實現(xiàn)了Ordered接口的BeanPostProcessors,順便根據(jù)Ordered排了序postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 最后加入其他常規(guī)的BeanPostProcessorsboolean reiterate = true;while (reiterate) {reiterate = false;postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);reiterate = true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();}// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. // 首先,加入實現(xiàn)了PriorityOrdered接口的BeanPostProcessors,順便根據(jù)PriorityOrdered排了序String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // 然后,加入實現(xiàn)了Ordered接口的BeanPostProcessors,順便根據(jù)Ordered排了序postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 最后加入其他常規(guī)的BeanPostProcessorsboolean reiterate = true;while (reiterate) {reiterate = false;postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);reiterate = true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();}根據(jù)排序接口返回值排序,默認升序排序,返回值越低優(yōu)先級越高。
/*** Useful constant for the highest precedence value.* @see java.lang.Integer#MIN_VALUE*/int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;/*** Useful constant for the lowest precedence value.* @see java.lang.Integer#MAX_VALUE*/int LOWEST_PRECEDENCE = Integer.MAX_VALUE;PriorityOrdered、Ordered接口作為Spring整個框架通用的排序接口,在Spring中應(yīng)用廣泛,也是非常重要的接口。
總結(jié)
Spring Bean的生命周期分為四個階段和多個擴展點。擴展點又可以分為影響多個Bean和影響單個Bean。整理如下:
四個階段
- 實例化 Instantiation
- 屬性賦值 Populate
- 初始化 Initialization
- 銷毀 Destruction
多個擴展點
- 影響多個Bean
- BeanPostProcessor
- InstantiationAwareBeanPostProcessor
- 影響單個Bean
- Aware
- Aware Group1
- BeanNameAware
- BeanClassLoaderAware
- BeanFactoryAware
- Aware Group2
- EnvironmentAware
- EmbeddedValueResolverAware
- ApplicationContextAware(ResourceLoaderAwareApplicationEventPublisherAwareMessageSourceAware)
- Aware Group1
- Aware
- 生命周期
- InitializingBean
- DisposableBean
- 生命周期
至此,Spring Bean的生命周期介紹完畢,由于作者水平有限難免有疏漏,歡迎留言糾錯。
總結(jié)
以上是生活随笔為你收集整理的nfvo通过调用哪个接口实现对vnf生命周期的管理_Spring-Bean生命周期的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第五人格园丁皮肤怎么得(《第五人格》官方
- 下一篇: mybatis支持驼峰自动转换sql吗_