詳解Spring 中 Bean 的生命周期
這其實(shí)是一道面試題,是我在面試百度的時(shí)候被問(wèn)到的,當(dāng)時(shí)沒(méi)有答出來(lái)(因?yàn)樽约赫娴暮懿?,后來(lái)在網(wǎng)上尋找答案,看到也是一頭霧水,直到看到了《Spring in action》這本書(shū),書(shū)上有對(duì)Bean聲明周期的大致解釋?zhuān)菦](méi)有代碼分析,所以就自己上網(wǎng)尋找資料,一定要把這個(gè)Bean生命周期弄明白!
網(wǎng)上大部分都是驗(yàn)證的Bean 在面試問(wèn)的生命周期,其實(shí)查閱JDK還有一個(gè)完整的Bean生命周期,這同時(shí)也驗(yàn)證了書(shū)是具有片面性的,最fresh 的資料還是查閱原始JDK!!!
一、Bean 的完整生命周期 在傳統(tǒng)的Java應(yīng)用中,bean的生命周期很簡(jiǎn)單,使用Java關(guān)鍵字 new 進(jìn)行Bean 的實(shí)例化,然后該Bean 就能夠使用了。一旦bean不再被使用,則由Java自動(dòng)進(jìn)行垃圾回收。
相比之下,Spring管理Bean的生命周期就復(fù)雜多了,正確理解Bean 的生命周期非常重要,因?yàn)镾pring對(duì)Bean的管理可擴(kuò)展性非常強(qiáng),下面展示了一個(gè)Bean的構(gòu)造過(guò)程

Bean 的生命周期
如上圖所示,Bean 的生命周期還是比較復(fù)雜的,下面來(lái)對(duì)上圖每一個(gè)步驟做文字描述:
Spring啟動(dòng),查找并加載需要被Spring管理的bean,進(jìn)行Bean的實(shí)例化 Bean實(shí)例化后對(duì)將Bean的引入和值注入到Bean的屬性中 如果Bean實(shí)現(xiàn)了BeanNameAware接口的話,Spring將Bean的Id傳遞給setBeanName()方法 如果Bean實(shí)現(xiàn)了BeanFactoryAware接口的話,Spring將調(diào)用setBeanFactory()方法,將BeanFactory容器實(shí)例傳入 如果Bean實(shí)現(xiàn)了ApplicationContextAware接口的話,Spring將調(diào)用Bean的setApplicationContext()方法,將bean所在應(yīng)用上下文引用傳入進(jìn)來(lái) 如果Bean實(shí)現(xiàn)了BeanPostProcessor接口,Spring就將調(diào)用他們的postProcessBeforeInitialization()方法。 如果Bean 實(shí)現(xiàn)了InitializingBean接口,Spring將調(diào)用他們的afterPropertiesSet()方法。類(lèi)似的,如果bean使用init-method聲明了初始化方法,該方法也會(huì)被調(diào)用 如果Bean 實(shí)現(xiàn)了BeanPostProcessor接口,Spring就將調(diào)用他們的postProcessAfterInitialization()方法。 此時(shí),Bean已經(jīng)準(zhǔn)備就緒,可以被應(yīng)用程序使用了。他們將一直駐留在應(yīng)用上下文中,直到應(yīng)用上下文被銷(xiāo)毀。 如果bean實(shí)現(xiàn)了DisposableBean接口,Spring將調(diào)用它的destory()接口方法,同樣,如果bean使用了destory-method 聲明銷(xiāo)毀方法,該方法也會(huì)被調(diào)用。上面是Spring 中Bean的核心接口和生命周期,面試回答上述過(guò)程已經(jīng)足夠了。但是翻閱JavaDoc文檔發(fā)現(xiàn)除了以上接口外,還有另外的初始化過(guò)程涉及的接口:
摘自org.springframework.beans.factory.BeanFactory, 全部相關(guān)接口如下,上述已有的就不用著重標(biāo)注,把額外的相關(guān)接口著重標(biāo)注下

Bean 完整的生命周期
文字解釋如下:
————————————初始化————————————
BeanNameAware.setBeanName() 在創(chuàng)建此bean的bean工廠中設(shè)置bean的名稱(chēng),在普通屬性設(shè)置之后調(diào)用,在InitializinngBean.afterPropertiesSet()方法之前調(diào)用 BeanClassLoaderAware.setBeanClassLoader(): 在普通屬性設(shè)置之后,InitializingBean.afterPropertiesSet()之前調(diào)用 BeanFactoryAware.setBeanFactory() : 回調(diào)提供了自己的bean實(shí)例工廠,在普通屬性設(shè)置之后,在InitializingBean.afterPropertiesSet()或者自定義初始化方法之前調(diào)用 EnvironmentAware.setEnvironment(): 設(shè)置environment在組件使用時(shí)調(diào)用 EmbeddedValueResolverAware.setEmbeddedValueResolver(): 設(shè)置StringValueResolver 用來(lái)解決嵌入式的值域問(wèn)題 ResourceLoaderAware.setResourceLoader(): 在普通bean對(duì)象之后調(diào)用,在afterPropertiesSet 或者自定義的init-method 之前調(diào)用,在 ApplicationContextAware 之前調(diào)用。 ApplicationEventPublisherAware.setApplicationEventPublisher(): 在普通bean屬性之后調(diào)用,在初始化調(diào)用afterPropertiesSet 或者自定義初始化方法之前調(diào)用。在 ApplicationContextAware 之前調(diào)用。 MessageSourceAware.setMessageSource(): 在普通bean屬性之后調(diào)用,在初始化調(diào)用afterPropertiesSet 或者自定義初始化方法之前調(diào)用,在 ApplicationContextAware 之前調(diào)用。 ApplicationContextAware.setApplicationContext(): 在普通Bean對(duì)象生成之后調(diào)用,在InitializingBean.afterPropertiesSet之前調(diào)用或者用戶(hù)自定義初始化方法之前。在ResourceLoaderAware.setResourceLoader,ApplicationEventPublisherAware.setApplicationEventPublisher,MessageSourceAware之后調(diào)用。 ServletContextAware.setServletContext(): 運(yùn)行時(shí)設(shè)置ServletContext,在普通bean初始化后調(diào)用,在InitializingBean.afterPropertiesSet之前調(diào)用,在 ApplicationContextAware 之后調(diào)用注:是在WebApplicationContext 運(yùn)行時(shí) BeanPostProcessor.postProcessBeforeInitialization() : 將此BeanPostProcessor 應(yīng)用于給定的新bean實(shí)例 在任何bean初始化回調(diào)方法(像是InitializingBean.afterPropertiesSet或者自定義的初始化方法)之前調(diào)用。這個(gè)bean將要準(zhǔn)備填充屬性的值。返回的bean示例可能被普通對(duì)象包裝,默認(rèn)實(shí)現(xiàn)返回是一個(gè)bean。 BeanPostProcessor.postProcessAfterInitialization() : 將此BeanPostProcessor 應(yīng)用于給定的新bean實(shí)例 在任何bean初始化回調(diào)方法(像是InitializingBean.afterPropertiesSet或者自定義的初始化方法)之后調(diào)用。這個(gè)bean將要準(zhǔn)備填充屬性的值。返回的bean示例可能被普通對(duì)象包裝 InitializingBean.afterPropertiesSet(): 被BeanFactory在設(shè)置所有bean屬性之后調(diào)用(并且滿足BeanFactory 和 ApplicationContextAware)。————————————銷(xiāo)毀————————————
在BeanFactory 關(guān)閉的時(shí)候,Bean的生命周期會(huì)調(diào)用如下方法:
DestructionAwareBeanPostProcessor.postProcessBeforeDestruction(): 在銷(xiāo)毀之前將此BeanPostProcessor 應(yīng)用于給定的bean實(shí)例。能夠調(diào)用自定義回調(diào),像是DisposableBean 的銷(xiāo)毀和自定義銷(xiāo)毀方法,這個(gè)回調(diào)僅僅適用于工廠中的單例bean(包括內(nèi)部bean)實(shí)現(xiàn)了自定義的destory()方法
二、Bean 的生命周期驗(yàn)證為了驗(yàn)證Bean生命周期的過(guò)程,有兩種形式:一種是為面試而準(zhǔn)備的,一種是為了解全過(guò)程而準(zhǔn)備的,下面來(lái)看代碼:
Book.class
public class Book implements BeanNameAware,BeanFactoryAware, ApplicationContextAware,InitializingBean,DisposableBean { private String bookName; public Book(){ System.out.println('Book Initializing '); } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println('Book.setBeanFactory invoke'); } public void setBeanName(String name) { System.out.println('Book.setBeanName invoke'); } public void destroy() throws Exception { System.out.println('Book.destory invoke'); } public void afterPropertiesSet() throws Exception { System.out.println('Book.afterPropertiesSet invoke'); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println('Book.setApplicationContext invoke'); } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; System.out.println('setBookName: Book name has set.'); } public void myPostConstruct(){ System.out.println('Book.myPostConstruct invoke'); } // 自定義初始化方法 @PostConstruct public void springPostConstruct(){ System.out.println('@PostConstruct'); } public void myPreDestory(){ System.out.println('Book.myPreDestory invoke'); System.out.println('---------------destroy-----------------'); } // 自定義銷(xiāo)毀方法 @PreDestroy public void springPreDestory(){ System.out.println('@PreDestory'); } @Override protected void finalize() throws Throwable { System.out.println('------inside finalize-----'); }}
自定義實(shí)現(xiàn)BeanPostProcessor 的MyBeanPostProcessor:
public class MyBeanPostProcessor implements BeanPostProcessor { // 容器加載的時(shí)候會(huì)加載一些其他的bean,會(huì)調(diào)用初始化前和初始化后方法 // 這次只關(guān)注book(bean)的生命周期 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Book){ System.out.println('MyBeanPostProcessor.postProcessBeforeInitialization'); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Book){ System.out.println('MyBeanPostProcessor.postProcessAfterInitialization'); } return bean; }}
在resources 目錄下新建Bean-Lifecycle.xml
<beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd'> <!-- 掃描bean --> <context:component-scan base-package='com.bean.lifecycle'/> <!-- 實(shí)現(xiàn)了用戶(hù)自定義初始化和銷(xiāo)毀方法 --> <bean init-method='myPostConstruct' destroy-method='myPreDestory'> <!-- 注入bean 屬性名稱(chēng) --> <property name='bookName' value='thingking in java' /> </bean> <!--引入自定義的BeanPostProcessor--> <bean /></beans>
做一個(gè)啟動(dòng)類(lèi)的測(cè)試,新建SpringBeanLifecycleApplication
public class SpringBeanLifecycleApplication { public static void main(String[] args) throws InterruptedException { // 為面試而準(zhǔn)備的Bean生命周期加載過(guò)程 ApplicationContext context = new ClassPathXmlApplicationContext('Bean-Lifecycle.xml'); Book book = (Book)context.getBean('book'); System.out.println('Book name = ' + book.getBookName()); ((ClassPathXmlApplicationContext) context).destroy(); }}
啟動(dòng)測(cè)試,輸出結(jié)果如下:
Book Initializing setBookName: Book name has set. Book.setBeanName invoke Book.setBeanFactory invoke Book.setApplicationContext invoke MyBeanPostProcessor.postProcessBeforeInitialization @PostConstruct Book.afterPropertiesSet invoke Book.myPostConstruct invoke MyBeanPostProcessor.postProcessAfterInitialization Book name = thingking in java
@PreDestory Book.destory invoke Book.myPreDestory invoke ---------------destroy-----------------
為了驗(yàn)證Bean完整的生命周期,需要新建一個(gè)SubBookClass 繼承Book類(lèi)
public class SubBookClass extends Book implements BeanClassLoaderAware, EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware, ApplicationEventPublisherAware,MessageSourceAware{ private String bookSystem; public String getBookSystem() { return bookSystem; } public void setBookSystem(String bookSystem) { System.out.println('設(shè)置BookSystem 的屬性值'); this.bookSystem = bookSystem; } public void setBeanClassLoader(ClassLoader classLoader) { System.out.println('SubBookClass.setBeanClassLoader() 方法被調(diào)用了'); } public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { System.out.println('SubBookClass.setApplicationEventPublisher() 方法被調(diào)用了'); } public void setEmbeddedValueResolver(StringValueResolver resolver) { System.out.println('SubBookClass.setEmbeddedValueResolver() 方法被調(diào)用了'); } public void setEnvironment(Environment environment) { System.out.println('SubBookClass.setEnvironment() 方法被調(diào)用了'); } public void setMessageSource(MessageSource messageSource) { System.out.println('SubBookClass.setMessageSource() 方法被調(diào)用了'); } public void setResourceLoader(ResourceLoader resourceLoader) { System.out.println('SubBookClass.setResourceLoader() 方法被調(diào)用了'); }}
上述SubBookClass類(lèi)與Book是互補(bǔ)關(guān)系。
新建一個(gè)SubBean-Lifecycle.xml,注入SubBookClass
<beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd'> <bean init-method='myPostConstruct' destroy-method='myPreDestory'> <property name='bookSystem' value='Java System' /> </bean> <bean /></beans>
完整的SpringBeanLifecycleApplication 如下:
public class SpringBeanLifecycleApplication { public static void main(String[] args) throws InterruptedException { // 為面試而準(zhǔn)備的Bean生命周期加載過(guò)程 ApplicationContext context = new ClassPathXmlApplicationContext('Bean-Lifecycle.xml'); Book book = (Book)context.getBean('book'); System.out.println('Book name = ' + book.getBookName()); ((ClassPathXmlApplicationContext) context).destroy(); // 完整的加載過(guò)程,當(dāng)然了解的越多越好 ApplicationContext applicationContext = new ClassPathXmlApplicationContext('SubBean-Lifecycle.xml'); SubBookClass subBookClass = (SubBookClass) applicationContext.getBean('bookClass'); System.out.println('BookSystemName = ' + subBookClass.getBookSystem()); ((ClassPathXmlApplicationContext) applicationContext).registerShutdownHook(); }}
輸出完整的結(jié)果:
Book Initializing setBookName: Book name has set. Book.setBeanName invoke Book.setBeanFactory invoke Book.setApplicationContext invoke MyBeanPostProcessor.postProcessBeforeInitialization @PostConstruct Book.afterPropertiesSet invoke Book.myPostConstruct invoke MyBeanPostProcessor.postProcessAfterInitialization Book name = thingking in java @PreDestory Book.destory invoke Book.myPreDestory invoke ---------------destroy-----------------
Book Initializing 設(shè)置BookSystem 的屬性值 Book.setBeanName invoke SubBookClass.setBeanClassLoader() 方法被調(diào)用了 Book.setBeanFactory invoke SubBookClass.setEnvironment() 方法被調(diào)用了 SubBookClass.setEmbeddedValueResolver() 方法被調(diào)用了 SubBookClass.setResourceLoader() 方法被調(diào)用了 SubBookClass.setApplicationEventPublisher() 方法被調(diào)用了 SubBookClass.setMessageSource() 方法被調(diào)用了 Book.setApplicationContext invoke MyBeanPostProcessor.postProcessBeforeInitialization Book.afterPropertiesSet invoke Book.myPostConstruct invoke MyBeanPostProcessor.postProcessAfterInitialization BookSystemName = Java System Book.destory invoke Book.myPreDestory invoke ---------------destroy-----------------
以上就是詳解Spring 中 Bean 的生命周期的詳細(xì)內(nèi)容,更多關(guān)于Spring 中 Bean 的生命周期的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備