Spring_bean的生命周期
1、单例对象(singleton)
初始化:容器创建时出生
存活:容器存在,bean对象存在
销毁:容器销毁时,bean对象死亡
bean.xml文件
<bean id="accountService" class="com.zl.service.impl.AccountServiceImpl" scope="singleton" init-method="init" destroy-method="destroy" ></bean>
调用方法
public static void main(String[] args) {
//1.获取核心容器对象
ClassPathXmlApplicationContext ac= new ClassPathXmlApplicationContext("bean.xml");
//2.根据对象id获取对象
IAccountService service=(IAccountService)ac.getBean("accountService");
System.out.println(service);
System.out.println("destroy beanContainer");
ac.close();//关闭容器
}
执行结果:

2、多例对象(prototype)
初始化:使用bean对象时,Spring框架才初始化bean对象
存活:bean对象在被使用时便活着
销毁:bean对象长时间没被引用,就会被Java的垃圾回收器回收销毁
bean.xml文件
<bean id="accountService" class="com.zl.service.impl.AccountServiceImpl" scope="prototype" init-method="init" destroy-method="destroy" ></bean>
调用方法
public static void main(String[] args) {
//1.获取核心容器对象
ClassPathXmlApplicationContext ac= new ClassPathXmlApplicationContext("bean.xml");
//2.根据对象id获取对象
IAccountService service=(IAccountService)ac.getBean("accountService");
System.out.println(service);
System.out.println("destroy beanContainer");
ac.close();//关闭容器
}
执行结果:

可见,当bean的scope属性为prototype时,及时关闭了容器,bean对象也还没有被销毁,因为Spring容器不清楚在bean的scope属性为多例的情况下,Spring框架不清楚多例bean对象们是否还被引用,所以需要由Java垃圾回收器回收。
本文深入解析Spring框架中Bean的两种作用域:singleton和prototype的生命周期。详细阐述了单例对象和多例对象从创建到销毁的过程,以及如何通过bean.xml配置文件中的scope属性来控制这些过程。
964

被折叠的 条评论
为什么被折叠?



