Spring_bean的生命周期

本文深入解析Spring框架中Bean的两种作用域:singleton和prototype的生命周期。详细阐述了单例对象和多例对象从创建到销毁的过程,以及如何通过bean.xml配置文件中的scope属性来控制这些过程。

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垃圾回收器回收。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值