生命周期控制
自定义配置
public class BookDaoImpl implements BookDao {
//表示bean创建前加载
public void init() {
System.out.println("init...");
}
@Override
public void save() {
System.out.println("book dao save");
}
//bean销毁前加载
public void destroy() {
System.out.println("destroy...");
}
}
//执行bean的销毁需要关闭容器,但是原本的applicationContext接口没有close实现
//需要使用另一个接口ConfigurableApplicationContext 提供
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao3");
bookDao.save();
//ctx.close(); 较为暴力的关闭方式 在当前位置直接关闭
ctx.registerShutdownHook(); //关闭钩子:容器启动以后,如果要关闭虚拟机,需要先关闭完容器
要实现初始化和销毁,还需要在对应bean配置
# init-method
# destroy-method
<bean id="bookDao" class="com.mvnweb.dao.impl.BookDaoImpl" init-method="init" destroy-method="destroy"/>
Spring提供了对应的规范接口(了解)
tips:afterPropertiesSet() 是在属性设置完以后才执行,与签名对应,严格规定了执行顺序
//InitializingBean
//DisposableBean
public class BookDaoImpl implements BookDao, InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("init...");
}
Bean生命周期
初始化容器
创建对象(内存分配)
执行构造方法
执行属性注入(set操作)
执行bean初始化方法
使用bean
执行业务操作
关闭,销毁容器
执行bean销毁方法
graph TB
subgraph 初始化容器
create[创建对象(内存分配)] --> Constructor[执行构造方法]
--> 属性注入 --> init[执行bean初始化方法]
end
subgraph 使用bean
save业务操作
end
subgraph 关闭销毁容器
destory[执行销毁方法]
end
初始化容器 --> 使用bean --> 关闭销毁容器
Bean销毁时机
关闭容器前触发bean的销毁
关闭容器方式:
手工关闭容器:ConfigurableApplicationContext接口close()操作
注册关闭钩子,在虚拟机退出前先关闭容器再退出虚拟机:ConfigurableApplicationContext接口registerShutdownHook()操作
tips:这两个接口方法是由它的实现类ClasspathXmlApplicationContext调用的