Spring Bean的生命周期詳細(xì)介紹
Spring作為當(dāng)前Java最流行、最強(qiáng)大的輕量級(jí)框架,受到了程序員的熱烈歡迎。準(zhǔn)確的了解Spring Bean的生命周期是非常必要的。我們通常使用ApplicationContext作為Spring容器。這里,我們講的也是 ApplicationContext中Bean的生命周期。而實(shí)際上BeanFactory也是差不多的,只不過(guò)處理器需要手動(dòng)注冊(cè)。
一、生命周期流程圖:
Spring Bean的完整生命周期從創(chuàng)建Spring容器開(kāi)始,直到最終Spring容器銷毀Bean,這其中包含了一系列關(guān)鍵點(diǎn)。
若容器注冊(cè)了以上各種接口,程序那么將會(huì)按照以上的流程進(jìn)行。下面將仔細(xì)講解各接口作用。
二、各種接口方法分類
Bean的完整生命周期經(jīng)歷了各種方法調(diào)用,這些方法可以劃分為以下幾類:
1、Bean自身的方法 ?。骸 ∵@個(gè)包括了Bean本身調(diào)用的方法和通過(guò)配置文件中<bean>的init-method和destroy-method指定的方法
2、Bean級(jí)生命周期接口方法 ?。骸 ∵@個(gè)包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這些接口的方法
3、容器級(jí)生命周期接口方法 ?。骸 ∵@個(gè)包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 這兩個(gè)接口實(shí)現(xiàn),一般稱它們的實(shí)現(xiàn)類為“后處理器”。
4、工廠后處理器接口方法 : 這個(gè)包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工廠后處理器 接口的方法。工廠后處理器也是容器級(jí)的。在應(yīng)用上下文裝配配置文件之后立即調(diào)用?! ?/p>
三、演示
我們用一個(gè)簡(jiǎn)單的Spring Bean來(lái)演示一下Spring Bean的生命周期。
1、首先是一個(gè)簡(jiǎn)單的Spring Bean,調(diào)用Bean自身的方法和Bean級(jí)生命周期接口方法,為了方便演示,它實(shí)現(xiàn)了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這4個(gè)接口,同時(shí)有2個(gè)方法,對(duì)應(yīng)配置文件中<bean>的init-method和destroy-method。如下:
package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** * @author qsk */ public class Person implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean { private String name; private String address; private int phone; private BeanFactory beanFactory; private String beanName; public Person() { System.out.println("【構(gòu)造器】調(diào)用Person的構(gòu)造器實(shí)例化"); } public String getName() { return name; } public void setName(String name) { System.out.println("【注入屬性】注入屬性name"); this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { System.out.println("【注入屬性】注入屬性address"); this.address = address; } public int getPhone() { return phone; } public void setPhone(int phone) { System.out.println("【注入屬性】注入屬性phone"); this.phone = phone; } @Override public String toString() { return "Person [address=" + address + ", name=" + name + ", phone=" + phone + "]"; } // 這是BeanFactoryAware接口方法 @Override public void setBeanFactory(BeanFactory arg0) throws BeansException { System.out .println("【BeanFactoryAware接口】調(diào)用BeanFactoryAware.setBeanFactory()"); this.beanFactory = arg0; } // 這是BeanNameAware接口方法 @Override public void setBeanName(String arg0) { System.out.println("【BeanNameAware接口】調(diào)用BeanNameAware.setBeanName()"); this.beanName = arg0; } // 這是InitializingBean接口方法 @Override public void afterPropertiesSet() throws Exception { System.out .println("【InitializingBean接口】調(diào)用InitializingBean.afterPropertiesSet()"); } // 這是DiposibleBean接口方法 @Override public void destroy() throws Exception { System.out.println("【DiposibleBean接口】調(diào)用DiposibleBean.destory()"); } // 通過(guò)<bean>的init-method屬性指定的初始化方法 public void myInit() { System.out.println("【init-method】調(diào)用<bean>的init-method屬性指定的初始化方法"); } // 通過(guò)<bean>的destroy-method屬性指定的初始化方法 public void myDestory() { System.out.println("【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法"); } }
2、接下來(lái)是演示BeanPostProcessor接口的方法,如下:
package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { public MyBeanPostProcessor() { super(); System.out.println("這是BeanPostProcessor實(shí)現(xiàn)類構(gòu)造器!!"); // TODO Auto-generated constructor stub } @Override public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessAfterInitialization對(duì)屬性進(jìn)行更改!"); return arg0; } @Override public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessBeforeInitialization對(duì)屬性進(jìn)行更改!"); return arg0; } }
如上,BeanPostProcessor接口包括2個(gè)方法postProcessAfterInitialization和postProcessBeforeInitialization,這兩個(gè)方法的第一個(gè)參數(shù)都是要處理的Bean對(duì)象,第二個(gè)參數(shù)都是Bean的name。返回值也都是要處理的Bean對(duì)象。這里要注意。
3、InstantiationAwareBeanPostProcessor 接口本質(zhì)是BeanPostProcessor的子接口,一般我們繼承Spring為其提供的適配器類InstantiationAwareBeanPostProcessor Adapter來(lái)使用它,如下:
package springBeanTest; import java.beans.PropertyDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { public MyInstantiationAwareBeanPostProcessor() { super(); System.out .println("這是InstantiationAwareBeanPostProcessorAdapter實(shí)現(xiàn)類構(gòu)造器!!"); } // 接口方法、實(shí)例化Bean之前調(diào)用 @Override public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessBeforeInstantiation方法"); return null; } // 接口方法、實(shí)例化Bean之后調(diào)用 @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessAfterInitialization方法"); return bean; } // 接口方法、設(shè)置某個(gè)屬性時(shí)調(diào)用 @Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessPropertyValues方法"); return pvs; } }
這個(gè)有3個(gè)方法,其中第二個(gè)方法postProcessAfterInitialization就是重寫(xiě)了BeanPostProcessor的方法。第三個(gè)方法postProcessPropertyValues用來(lái)操作屬性,返回值也應(yīng)該是PropertyValues對(duì)象。
4、演示工廠后處理器接口方法,如下:
package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public MyBeanFactoryPostProcessor() { super(); System.out.println("這是BeanFactoryPostProcessor實(shí)現(xiàn)類構(gòu)造器??!"); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException { System.out .println("BeanFactoryPostProcessor調(diào)用postProcessBeanFactory方法"); BeanDefinition bd = arg0.getBeanDefinition("person"); bd.getPropertyValues().addPropertyValue("phone", "110"); } }
5、配置文件如下beans.xml,很簡(jiǎn)單,使用ApplicationContext,處理器不用手動(dòng)注冊(cè):
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor"> </bean> <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor"> </bean> <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor"> </bean> <bean id="person" class="springBeanTest.Person" init-method="myInit" destroy-method="myDestory" scope="singleton" p:name="張三" p:address="廣州" p:phone="15900000000" /> </beans>
6、下面測(cè)試一下:
package springBeanTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanLifeCycle { public static void main(String[] args) { System.out.println("現(xiàn)在開(kāi)始初始化容器"); ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml"); System.out.println("容器初始化成功"); //得到Preson,并使用 Person person = factory.getBean("person",Person.class); System.out.println(person); System.out.println("現(xiàn)在開(kāi)始關(guān)閉容器!"); ((ClassPathXmlApplicationContext)factory).registerShutdownHook(); } }
關(guān)閉容器使用的是實(shí)際是AbstractApplicationContext的鉤子方法。
我們來(lái)看一下結(jié)果:
現(xiàn)在開(kāi)始初始化容器 2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy 2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml] 這是BeanFactoryPostProcessor實(shí)現(xiàn)類構(gòu)造器??! BeanFactoryPostProcessor調(diào)用postProcessBeanFactory方法 這是BeanPostProcessor實(shí)現(xiàn)類構(gòu)造器!! 這是InstantiationAwareBeanPostProcessorAdapter實(shí)現(xiàn)類構(gòu)造器!! 2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy InstantiationAwareBeanPostProcessor調(diào)用postProcessBeforeInstantiation方法 【構(gòu)造器】調(diào)用Person的構(gòu)造器實(shí)例化 InstantiationAwareBeanPostProcessor調(diào)用postProcessPropertyValues方法 【注入屬性】注入屬性address 【注入屬性】注入屬性name 【注入屬性】注入屬性phone 【BeanNameAware接口】調(diào)用BeanNameAware.setBeanName() 【BeanFactoryAware接口】調(diào)用BeanFactoryAware.setBeanFactory() BeanPostProcessor接口方法postProcessBeforeInitialization對(duì)屬性進(jìn)行更改! 【InitializingBean接口】調(diào)用InitializingBean.afterPropertiesSet() 【init-method】調(diào)用<bean>的init-method屬性指定的初始化方法 BeanPostProcessor接口方法postProcessAfterInitialization對(duì)屬性進(jìn)行更改! InstantiationAwareBeanPostProcessor調(diào)用postProcessAfterInitialization方法 容器初始化成功 Person [address=廣州, name=張三, phone=110] 現(xiàn)在開(kāi)始關(guān)閉容器! 【DiposibleBean接口】調(diào)用DiposibleBean.destory() 【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法
以上就是對(duì)Java Spring Bean 生命周期的資料整理,后續(xù)繼續(xù)補(bǔ)充相關(guān)資料,謝謝大家對(duì)本站的支持!
相關(guān)文章
POI導(dǎo)出Excel報(bào)錯(cuò)No such file or directory的解決方法
這篇文章主要為大家詳細(xì)介紹了POI導(dǎo)出Excel報(bào)錯(cuò)No such file or directory的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11詳解SpringBoot中的index首頁(yè)的訪問(wèn)、自定義Favicon圖標(biāo)
這篇文章主要介紹了SpringBoot中的index首頁(yè)的訪問(wèn)、自定義Favicon圖標(biāo),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08Springboot @Value獲取值為空問(wèn)題解決方案
這篇文章主要介紹了Springboot @Value獲取值為空問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02java中對(duì)象的強(qiáng)、軟、弱、虛四種引用詳解
這篇文章主要介紹了java中對(duì)象的強(qiáng)、軟、弱、虛四種引用詳解,對(duì)象的引用分為4種,分別是強(qiáng)引用>軟引用>弱引用>虛引用,程序員可以通過(guò)不同的引用控制對(duì)象的生命周期,方便垃圾回收,使程序更加靈活的控制對(duì)象生命周期,需要的朋友可以參考下2023-09-09springboot dynamic多數(shù)據(jù)源demo以及常見(jiàn)切換、事務(wù)的問(wèn)題
這篇文章主要介紹了springboot dynamic多數(shù)據(jù)源demo以及常見(jiàn)切換、事務(wù)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07