問題:Spring Bean的生命周期 ?
bean
元素被實(shí)例化,和被銷毀的過程。我們通過init-method
屬性指定初始化方法; 通過destroy-method
方法指定銷毀方法。Spring Bean
的生命周期是非常必要的。我們通常使用 ApplicationContext
作為 Spring 容器。這里,我們講的也是 ApplicationContext
中 Bean
的生命周期。而實(shí)際上 BeanFactory
也是差不多的,只不過處理器需要手動(dòng)注冊(cè)。一、生命周期流程圖:
Spring Bean
的完整生命周期從創(chuàng)建 Spring
容器開始,直到最終 Spring
容器銷毀 Bean
,這其中包含了一系列關(guān)鍵點(diǎn)。
若容器注冊(cè)了以上各種接口,程序那么將會(huì)按照以上的流程進(jìn)行。下面將仔細(xì)講解各接口作用。
二、各種接口方法分類
Bean
的完整生命周期經(jīng)歷了各種方法調(diào)用,這些方法可以劃分為以下幾類:
1、Bean
自身的方法:這個(gè)包括了 Bean
本身調(diào)用的方法和通過配置文件中<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)用。
三、演示
我們用一個(gè)簡(jiǎn)單的 Spring Bean 來演示一下 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。如下:
1 package springBeanTest;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.beans.factory.BeanFactory;
5 import org.springframework.beans.factory.BeanFactoryAware;
6 import org.springframework.beans.factory.BeanNameAware;
7 import org.springframework.beans.factory.DisposableBean;
8 import org.springframework.beans.factory.InitializingBean;
9
10 /**
11 * @author qsk
12 */
13 public class Person implements BeanFactoryAware, BeanNameAware,
14 InitializingBean, DisposableBean {
15
16 private String name;
17 private String address;
18 private int phone;
19
20 private BeanFactory beanFactory;
21 private String beanName;
22
23 public Person() {
24 System.out.println("【構(gòu)造器】調(diào)用Person的構(gòu)造器實(shí)例化");
25 }
26
27 public String getName() {
28 return name;
29 }
30
31 public void setName(String name) {
32 System.out.println("【注入屬性】注入屬性name");
33 this.name = name;
34 }
35
36 public String getAddress() {
37 return address;
38 }
39
40 public void setAddress(String address) {
41 System.out.println("【注入屬性】注入屬性address");
42 this.address = address;
43 }
44
45 public int getPhone() {
46 return phone;
47 }
48
49 public void setPhone(int phone) {
50 System.out.println("【注入屬性】注入屬性phone");
51 this.phone = phone;
52 }
53
54 @Override
55 public String toString() {
56 return "Person [address=" + address + ", name=" + name + ", phone="
57 + phone + "]";
58 }
59
60 // 這是BeanFactoryAware接口方法
61 @Override
62 public void setBeanFactory(BeanFactory arg0) throws BeansException {
63 System.out
64 .println("【BeanFactoryAware接口】調(diào)用BeanFactoryAware.setBeanFactory()");
65 this.beanFactory = arg0;
66 }
67
68 // 這是BeanNameAware接口方法
69 @Override
70 public void setBeanName(String arg0) {
71 System.out.println("【BeanNameAware接口】調(diào)用BeanNameAware.setBeanName()");
72 this.beanName = arg0;
73 }
74
75 // 這是InitializingBean接口方法
76 @Override
77 public void afterPropertiesSet() throws Exception {
78 System.out
79 .println("【InitializingBean接口】調(diào)用InitializingBean.afterPropertiesSet()");
80 }
81
82 // 這是DiposibleBean接口方法
83 @Override
84 public void destroy() throws Exception {
85 System.out.println("【DiposibleBean接口】調(diào)用DiposibleBean.destory()");
86 }
87
88 // 通過<bean>的init-method屬性指定的初始化方法
89 public void myInit() {
90 System.out.println("【init-method】調(diào)用<bean>的init-method屬性指定的初始化方法");
91 }
92
93 // 通過<bean>的destroy-method屬性指定的初始化方法
94 public void myDestory() {
95 System.out.println("【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法");
96 }
97 }
2、接下來是演示 BeanPostProcessor
接口的方法,如下:
1 package springBeanTest;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.beans.factory.config.BeanPostProcessor;
5
6 public class MyBeanPostProcessor implements BeanPostProcessor {
7
8 public MyBeanPostProcessor() {
9 super();
10 System.out.println("這是BeanPostProcessor實(shí)現(xiàn)類構(gòu)造器??!");
11 // TODO Auto-generated constructor stub
12 }
13
14 @Override
15 public Object postProcessAfterInitialization(Object arg0, String arg1)
16 throws BeansException {
17 System.out
18 .println("BeanPostProcessor接口方法postProcessAfterInitialization對(duì)屬性進(jìn)行更改!");
19 return arg0;
20 }
21
22 @Override
23 public Object postProcessBeforeInitialization(Object arg0, String arg1)
24 throws BeansException {
25 System.out
26 .println("BeanPostProcessor接口方法postProcessBeforeInitialization對(duì)屬性進(jìn)行更改!");
27 return arg0;
28 }
29 }
如上,BeanPostProcessor
接口包括2個(gè)方法 postProcessAfterInitialization
和 postProcessBeforeInitialization
,這兩個(gè)方法的第一個(gè)參數(shù)都是要處理的 Bean
對(duì)象,第二個(gè)參數(shù)都是 Bean
的 name
。返回值也都是要處理的 Bean
對(duì)象。這里要注意。
3、InstantiationAwareBeanPostProcessor
接口本質(zhì)是 BeanPostProcessor
的子接口,一般我們繼承 Spring
為其提供的適配器類 InstantiationAwareBeanPostProcessor Adapter
來使用它,如下:
1 package springBeanTest;
2
3 import java.beans.PropertyDescriptor;
4
5 import org.springframework.beans.BeansException;
6 import org.springframework.beans.PropertyValues;
7 import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
8
9 public class MyInstantiationAwareBeanPostProcessor extends
10 InstantiationAwareBeanPostProcessorAdapter {
11
12 public MyInstantiationAwareBeanPostProcessor() {
13 super();
14 System.out
15 .println("這是InstantiationAwareBeanPostProcessorAdapter實(shí)現(xiàn)類構(gòu)造器!!");
16 }
17
18 // 接口方法、實(shí)例化Bean之前調(diào)用
19 @Override
20 public Object postProcessBeforeInstantiation(Class beanClass,
21 String beanName) throws BeansException {
22 System.out
23 .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessBeforeInstantiation方法");
24 return null;
25 }
26
27 // 接口方法、實(shí)例化Bean之后調(diào)用
28 @Override
29 public Object postProcessAfterInitialization(Object bean, String beanName)
30 throws BeansException {
31 System.out
32 .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessAfterInitialization方法");
33 return bean;
34 }
35
36 // 接口方法、設(shè)置某個(gè)屬性時(shí)調(diào)用
37 @Override
38 public PropertyValues postProcessPropertyValues(PropertyValues pvs,
39 PropertyDescriptor[] pds, Object bean, String beanName)
40 throws BeansException {
41 System.out
42 .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessPropertyValues方法");
43 return pvs;
44 }
45 }
這個(gè)有3個(gè)方法,其中第二個(gè)方法 postProcessAfterInitialization
就是重寫了 BeanPostProcessor
的方法。第三個(gè)方法 postProcessPropertyValues
用來操作屬性,返回值也應(yīng)該是 PropertyValues
對(duì)象。
4、演示工廠后處理器接口方法,如下:
1 package springBeanTest;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.beans.factory.config.BeanDefinition;
5 import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
6 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
7
8 public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
9
10 public MyBeanFactoryPostProcessor() {
11 super();
12 System.out.println("這是BeanFactoryPostProcessor實(shí)現(xiàn)類構(gòu)造器!!");
13 }
14
15 @Override
16 public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
17 throws BeansException {
18 System.out
19 .println("BeanFactoryPostProcessor調(diào)用postProcessBeanFactory方法");
20 BeanDefinition bd = arg0.getBeanDefinition("person");
21 bd.getPropertyValues().addPropertyValue("phone", "110");
22 }
23
24 }
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è)試一下:
1 package springBeanTest;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5
6 public class BeanLifeCycle {
7
8 public static void main(String[] args) {
9
10 System.out.println("現(xiàn)在開始初始化容器");
11
12 ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");
13 System.out.println("容器初始化成功");
14 //得到Preson,并使用
15 Person person = factory.getBean("person",Person.class);
16 System.out.println(person);
17
18 System.out.println("現(xiàn)在開始關(guān)閉容器!");
19 ((ClassPathXmlApplicationContext)factory).registerShutdownHook();
20 }
21 }
關(guān)閉容器使用的是實(shí)際是 AbstractApplicationContext
的鉤子方法。
我們來看一下結(jié)果:
現(xiàn)在開始初始化容器
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)在開始關(guān)閉容器!
【DiposibleBean接口】調(diào)用DiposibleBean.destory()
【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法
更多建議: