手动配置
在 BooDaoImpl 类中分别添加两个方法,方法名任意
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 destory(){
System.out.println("destory...");
}
}
在配置文件添加配置,如下:
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
使用接口
修改 BookServiceImpl 类,添加两个接口InitializingBean
, DisposableBean
并实现接口中的两个方法afterPropertiesSet
和destroy
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
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");
}
}
对于 bean 的生命周期控制在 bean 的整个生命周期中所处的位置如下:
- 初始化容器
- 1.创建对象(内存分配)
- 2.执行构造方法
- 3.执行属性注入(set 操作)
- 4.执行 bean 初始化方法
- 使用 bean
- 1.执行业务操作
- 关闭/销毁容器
- 1.执行 bean 销毁方法
关闭容器
close 关闭容器
-
ApplicationContext 中没有 close 方法
-
需要将 ApplicationContext 更换成 ClassPathXmlApplicationContext
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
-
调用 ctx 的 close()方法
ctx.close();
注册钩子关闭容器
-
在容器未关闭之前,提前设置好回调函数,让 JVM 在退出之前回调此函数来关闭容器
-
调用 ctx 的 registerShutdownHook()方法
ctx.registerShutdownHook();
注意:registerShutdownHook 在 ApplicationContext 中也没有
相同点:这两种都能用来关闭容器
不同点:close()是在调用的时候关闭,registerShutdownHook()是在 JVM 退出前调用关闭。