Bean生命周期:定义 --- 初始化 --- 使用 --- 销毁
一.初始化:
方法1.实现org.springframework.beans.foctory.InitializingBean接口,覆盖afterPropertiesSet方法。系统会自动查找afterPropertiesSet方 法,执行其中的初始化操作
方法2.配置init-method
例如设置bean中init-method="init"那么在初始化过程中就会调用相应class指定类的init()方法进行初始化工作
二 销毁(与初始化类似)
方法1.实现org.springframework.beans.foctory.DisposableBean接口,覆盖destory方法。
方法2.配置destory-method
三 配置全局初始化、销毁方法(属于默认配置,参考截图)
注意:
1.当三种方式同时使用时,全局(默认的)初始化销毁方法会被覆盖。
2.另外实现接口(InitializingBean,DisposableBean)的初始化/销毁方式会先于配置文件中的初始化/销毁方式执行。
3.xml中配置了,但是类文件即使没有以上接口和全局初始化方法也是可以编译执行的,bean中配置了却没有实现bean中的init和destory等会报错。
例子:
public class BeanLifeCycle implements InitializingBean,DisposableBean{ public void start(){ System.out.println("Bean start"); } public void stop(){ System.out.println("Bean stop"); } public void destroy() throws Exception { System.out.println("destory"); } public void afterPropertiesSet() throws Exception { System.out.println("after properties"); } public void defaultInit(){ System.out.println("defaultInit"); } public void defaultDestory(){ System.out.println("defaultDestory"); } }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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-init-method="defaultInit" default-destroy-method="defaultDestory"> <bean id="beanLifeCycle" class="com.daley.springprac.prac1.lifecyle.BeanLifeCycle" init-method="start" destroy-method="stop"/> </beans>
优先级:接口>局部(有局部就不执行全局默认方法)
demo地址(文件夹prac1):https://github.com/DaleyChao/SpringPractice/tree/a1ee3afc0accc8ae796e17dea5edf8fdbeb61fa7