SpringBean生命周期
在传统的Java应用中,Bean的生命周期很简单,使用关键字new实例化Bean,当不需要该Bean时,由Java自动进行垃圾回收。

Spring中Bean的生命周期较复杂,可以表示为:Bean的定义->Bean的初始化->Bean的使用->Bean的销毁。
Spring根据Bean的作用域来选择管理方式。对于singleton作用域的Bean,Spring能够精确地知道该Bean何时被创建,何时初始化完成,以及何时被销毁;而对于prototype作用域的Bean,Spring只负责创建,当容器创建了Bean的实例后,Bean的实例就交给客户端代码管理,Spring容器将不再跟踪其生命周期。
SpringBean生命周期执行流程
Spring容器在确保一个Bean能够使用之前,会进行很多工作。Spring容器中Bean的生命周期流程如下图所示。

Bean生命周期的整个执行过程描述如下。
1、Spring启动,查找并加载需要被Spring管理的Bean,并实例化Bean。
2、利用依赖注入完成Bean中所有属性值的配置注入。
3、如果Bean实现了BeanNameAware接口,则Spring调用Bean的setBeanName()方法传入当前Bean的id值。
4、如果Bean实现了BeanFactoryAware接口,则Spring调用setBeanFactory()方法传入当前工厂实例的引用。
5、如果Bean实现了ApplicationContextAware接口,则Spring调用setApplicationContext()方法传入当前ApplicationContext实例的引用。
6、如果Bean实现了BeanPostProcessor接口,则Spring调用该接口的预初始化方法postProcessBeforeInitialzation()对Bean进行加工操作,此处非常重要,Spring的AOP就是利用它实现的。
7、如果Bean实现了InitializingBean接口,则Spring将调用afterPropertiesSet()方法。
8、如果在配置文件中通过init-method属性指定了初始化方法,则调用该初始化方法。
9、如果BeanPostProcessor和Bean关联,则Spring将调用该接口的初始化方法postProcessAfterInitialization()。此时,Bean已经可以被应用系统使用了。
10如果在<bean>中指定了该Bean的作用域为singleton,则将该Bean放入SpringIoC的缓存池中,触发Spring对该Bean的生命周期管理;如果在<bean>中指定了该Bean的作用域为prototype,则将该Bean交给调用者,调用者管理该Bean的生命周期,Spring不再管理1该Bean。
11、如果Bean实现了DisposableBean接口,则Spring会调用destory()方法销毁Bean;如果在配置文件中通过destory-method属性指定了Bean的销毁方法,则Spring将调用该方法对Bean进行销毁。
Spring为Bean提供了细致全面的生命周期过程,实现特定的接口或设置<bean>的属性都可以对Bean的生命周期过程产生影响。建议不要过多的使用Bean实现接口,因为这样会导致代码的耦合性过高。
了解Spring生命周期的意义就在于,可以利用Bean在其存活期间的指定时刻完成一些相关操作。一般情况下,会在Bean被初始化后和被销毁前执行一些相关操作。
Spring官方提供了3种方法实现初始化回调和销毁回调:
1、实现InitializingBean和DisposableBean接口;
2、在XML中配置init-method和destory-method;
3、使用@PostConstruct和@PreDestory注解。
在一个Bean中有多种生命周期回调方法时,优先级为:注解>接口>XML。
不建议使用接口和注解,这会让 pojo 类和 Spring 框架紧耦合。1复制代码类型:[java]
初始化回调
1.使用接口
org.springframework.beans.factory.InitializingBean接口提供了以下方法:
void afterPropertiesSet() throws Exception;1复制代码类型:[java]
您可以实现以上接口,在afterPropertiesSet方法内指定Bean初始化后需要执行的操作。
<bean id="..." class="..." />public class User implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("调用接口:InitializingBean,方法:afterPropertiesSet,无参数"); } }1234567复制代码类型:[java]
2.配置XML
可以通过init-method属性指定Bean初始化后执行的方法。
<bean id="..." class="..." init-method="init"/>public class User { public void init() { System.out.println("调用init-method指定的初始化方法:init" ); } }123456复制代码类型:[java]
3.使用注解
使用@PostConstruct注解标明该方法为Bean初始化后的方法。
public class ExampleBean { @PostConstruct public void init() { System.out.println("@PostConstruct注解指定的初始化方法:init" ); } }123456复制代码类型:[java]
销毁回调
1.使用接口
org.springframework.beans.factory.DisposableBean接口提供了以下方法:
void destroy() throws Exception;1复制代码类型:[java]
您可以实现以上接口,在destroy方法内指定Bean初始化后需要执行的操作。
<bean id="..." class="..." />public class User implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("调用接口:InitializingBean,方法:afterPropertiesSet,无参数"); } }1234567复制代码类型:[java]
2.配置XML
可以通过destroy-method属性指定Bean销毁后执行的方法。
<bean id="..." class="..." destroy-method="destroy"/>public class User { public void destroy() { System.out.println("调用destroy-method指定的销毁方法:destroy" ); } }123456复制代码类型:[java]
3.使用注解
使用@PreDestory注解标明该方法为Bean销毁前执行的方法。
public class ExampleBean { @PreDestory public void destroy() { System.out.println("@PreDestory注解指定的初始化方法:destroy" ); } }123456复制代码类型:[java]
示例
下面使用EclipseIDE演示如何通过配置XML的方式实现初始化回调和销毁回调,步骤如下:
1、创建SpringDemo项目,并在src目录下创建net.biancheng包。
2、添加相应的jar包,可以参考《第一个Spring程序》一节。
3、在net.biancheng包下创建HelloWorld和MainApp类。
4、在src目录下创建Spring配置文件Beans.xml。
5、运行SpringDemo项目。
HelloWorld类代码如下。
package net.biancheng;public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("message : " + message); } public void init() { System.out.println("Bean正在进行初始化"); } public void destroy() { System.out.println("Bean将要被销毁"); } }12345678910111213141516复制代码类型:[java]
MainApp类代码如下,该类中我们使用AbstractApplicationContext类的registerShutdownHook()方法,来确保正常关机并调用相关的destroy()方法。
package net.biancheng;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } }1234567891011复制代码类型:[java]
Beans.xml配置文件代码如下。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="helloWorld" class="net.biancheng.HelloWorld" init-method="init" destroy-method="destroy"> <property name="message" value="Hello World!" /> </bean> </beans>12345678910复制代码类型:[java]
运行结果如下。
Bean正在进行初始化 message : Hello World! Bean将要被销毁123复制代码类型:[java]
默认的初始化和销毁方法
如果多个Bean需要使用相同的初始化或者销毁方法,不用为每个bean声明初始化和销毁方法,可以使用default-init-method和default-destroy-method属性,如下所示。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-init-method="init" default-destroy-method="destroy"> <bean id="..." class="..."> ... </bean> </beans>