1. 给Bean设置生命周期方法
1.1. 单实例Bean
1 |
|
1 | <bean id="car" class="bean.Car" init-method="init" destroy-method="destroy" /> |
1 |
|
运行测试方法,发现只能看到init()被调用,没有看到destroy()。原因是程序运行完后,spring容器没来得及销毁bean,进程立即就结束了。1
调用init()
IOC容器其实有一个close方法,只是ApplicationContext接口没有1
2
3
4
5
6
7
8
9
public void test() throws Exception {
// 将ApplicationContext修改为子接口ConfigurableApplicationContext
ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car1 = (Car) ioc.getBean("car");
Car car2 = (Car) ioc.getBean("car");
// 手动销毁IOC容器
ioc.close();
}
运行,可以看到init和destroy都被调用了。可以得知,单实例Bean的生命周期为:
- 容器创建之后,实例化Bean,为Bean设置属性,调用init-method
- 容器销毁之前,调用Bean的destroy-method
1 | 调用init() |
1.2. 多实例Bean
1 | <bean id="car" class="bean.Car" scope="prototype" |
1 |
|
运行,可以看到每一次获取Bean,都会创建新的对象,并调用init()。但是容器关闭时,destroy-method没有被调用。可以得知,多实例Bean的生命周期为:
- 容器创建之后。每一次获取Bean时,实例化新的Bean,为Bean设置属性,调用init-method
- 容器销毁时,不会调用Bean的destroy-method
1 | 调用init() |