Spring中bean的生命周期
生命周期:从创建到销毁的过程
一. 初始化容器
- 创建对象
- 执行构造方法
- 执行属性注入(set方法)
- 执行bean初始化方法
二. 使用bean
- 执行业务操作
三. 关闭、销毁容器
- 执行bean销毁方法
案例
项目目录
配置
<!--init-method:设置bean初始化生命周期回调函数-->
<!--destroy-method:设置bean销毁生命周期回调函数,仅适用于单例对象-->
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destroy"/>
BookDaoImpl
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
//表示bean初始化对应的操作
public void init(){
System.out.println("init...");
}
//表示bean销毁前对应的操作
public void destroy(){
System.out.println("destory...");
}
}
BookDaoImpl
接口:
InitialzingBean
DisposaleBean
(还是常用上面配置的方式,这种方式做了解)
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set .....");
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
public void destroy() throws Exception {
System.out.println("service destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("service init");
}
}
AppForLifeCycle
为什么这里不使用 ApplicationContext 而是使用它的子类 ClassPathXmlApplicationContext 呢?因为 ClassPathXmlApplicationContext 中有destroy销毁方法(用来销毁容器,容器销毁了,Bean自然就没了),而ApplicationContext 中没有这个销毁方法,演示的时候,就体现不出来了。
public class AppForLifeCycle {
public static void main( String[] args ) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// ApplicationContext
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
//注册关闭钩子函数,在虚拟机退出之前回调此函数,关闭容器
ctx.registerShutdownHook();
//关闭容器
// ctx.close();
}
}
输出
- 创建对象
- 执行构造方法
- 执行属性注入(set方法)
- 执行bean初始化方法
- 执行业务操作
- 执行bean销毁方法
生命周期详解: 小鱼儿的博客