spring bean的生命周期
名称: init-method, destroy-method
类型:属性
归属: bean标签
作用:定义bean对象在初始化或销段时完成的工作
格式:<bean init-methoda"init" destroy-method-"deatroy>
取值: bean对应的类中对应的具体方法名
public class UserServiceImpl implements UserService {
UserServiceImpl (){
System.out.println("镜音铃来啦");
}
public void init(){
System.out.println("初始化bean");
}
public void save() {
System.out.println("洛天依,米库");
}
public void destory(){
System.out.println("死亡bean");
}
}
spring配置文件
<!--bean的scope属性-->
<bean id="userService" scope="singleton" init-method="init" destroy-method="destory" class="com.itheima.service.impl.UserServiceImpl"/>
init-method=“init” 意思是将init方法设置为初始化方法
destroy-method=“destory” 意思是将destory方法设置为销毁方法
他们后面的值 是方法的名称
控制台的显示信息
注意 scope=“singleton” 是单列的对象
初始化bean
spring配置文件
<!--bean的scope属性-->
<bean id="userService" scope="prototype" init-method="init" destroy-method="destory" class="com.itheima.service.impl.UserServiceImpl"/>
控制台的显示信息
注意 scope=“prototype” 是非单列的对象
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
要运行销毁方法要用到ClassPathXmlApplicationContext 的close方法
但是 ApplicationContext对象是不能使用ClassPathXmlApplicationContext的close方法
所以要用ClassPathXmlApplicationContext对象来获取bean的class属性
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取资源
UserService userService1 = (UserService)ctx.getBean("userService");
UserService userService2 = (UserService)ctx.getBean("userService");
UserService userService3 = (UserService)ctx.getBean("userService");
ctx.close();
这样控制台输出的是
控制台的显示信息
注意 scope=“singleton” 是单列的对象
运行destroy方法
镜音铃来啦
初始化bean
死亡bean
控制台的显示信息
注意 scope=“prototype” 是非单列的对象
不运行destroy方法
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
这是因为prototype 不归spring的容器管理,也就是非单列没有将对象放到spring的容器中,运行的结束是将spring容器给关闭,没有放在容器中也就不会在容器关闭是执行
注意事项:
1.当scope="singleton"时, spring容器中有且仅有一个对象, init方法在创建容器时仅执行一次
2.当scope="prototype"时, spring容器要创建同一类型的多个对象, init方法在每个对象创建时均执行一次
3.当scope="singleton"时,关闭容器会导致bean实例的销段,调用destroy方法一次
4.当scope="prototype"时,对象的销毁由垃圾回收机制gc0)控制, destroy方法将不会被执行