spring bean生命周期包含bean定义、初始化、使用及销毁等阶段。
bean定义指的是在xml文件中配置bean或bean类中注解bean,bean使用即从springcontext中获取已经初始化的bean并应用的过程,本文主要介绍bean的初始化及销毁阶段。
一、配置实现spring bean初始化、销毁的方式
1、xml文件中配置bean的init-method属性和destroy-method属性
xml配置文件:
<bean name="beanScope" class="com.jsun.test.springDemo.BeanScope" init-method="init_m" destroy-method="destroy_m"></bean>
BeanScope类:
public class BeanScope {
public BeanScope(){
System.out.println("BeanScope bean 实例化");
}
public void init_m(){
System.out.println("init-method 初始化");
}
public void destroy_m(){
System.out.println("destroy-method 销毁");
}
}
执行结果:
。。。Loading SpringContext
BeanScope bean 实例化
init-method 初始化
beanScope hashCode:969824969
。。。Closing SpringContext
destroy-method 销毁
从上面执行结果可以看出,bean的实例化构造器要先于初始化方法执行。
同时需要注意的是:如果bean中配置init-method和init-destroy属性,那么在bean类中必须提供对应的初始化和销毁方法,否则将抛出初始化异常:Exception encountered during context initialization
2、配置全局默认的初始化和销毁方法
<beans
...
default-init-method="init_d_m" default-destroy-method="destroy_d_m">
<bean name="beanScope" class="com.jsun.test.springDemo.BeanScope"></bean>
</beans>
BeanScope类:
public class BeanScope {
public BeanScope(){
System.out.println("BeanScope bean 实例化");
}
public void init_d_m(