1.添加初始化和销毁方法
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...");
}
}
2.配置生命周期
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init"
destroy-method="destory"/>
3.运行
运行发现,init方法执行了,但是destroy方法却未执行,这是为什么呢?
Spring的IOC容器是运行在JVM中。运行main方法后,JVM启动,Spring加载配置文件生成IOC容器,从容器获取bean对象,然后调方法执行main方法执行完后,JVM退出,这个时候IOC容器中的bean还没有来得及销毁就已经结束了,所以没有调用对应的destroy方法。
4.关闭容器的方法
1.close方法
public class app{
public static void main(String{} args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = BookService(ctx.getBean(bookService))
bookService.save();
ctx.close();
}
}
ApplicationContext中没有close方法,需要将ApplicationContext更换成ClassPathXmlApplicationContext。
2.注册钩子关闭容器
public class app{
public static void main(String{} args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.registerShutdownHook();
BookService bookService = BookService(ctx.getBean(bookService))
bookService.save();
}
}
registerShutdownHook在ApplicationContext中也没有。close()是在调用的时候关闭,registerShutdownHook()是在JVM退出前调用关闭。
3.利用接口实现生命周期控制
在BookServiceImpl完成这两个接口的使用,修改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");
}
}
初始化方法会在类中属性设置之后执行。