bean的生命周期

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");
	}
}

初始化方法会在类中属性设置之后执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值