Spring五类作用域,及不同作用域的bean相互依赖的问题

本文详细介绍了Spring框架中的五种作用域:singleton、prototype、request、session 和 globalsession,并重点探讨了 singleton 和 prototype 两种作用域在实际应用中的区别,特别是它们在相互依赖时可能遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring作用域:singleton,prototype,request,session,global session。

  1. singleton,单例模式,Spring默认也是单例模式。
    一个bean定义为singleton,Spring IOC只会创建该bean的唯一实例,储存到单例缓存,后续再创建该bean的实例时,会使用已经被储存的 缓存。
<bean id="SpringIocDao" class="ioc.dao.SpringIocDaoIpml" scope="singleton">
  1. prototype
    一个bean定义为prototype,每一次对该bean的请求(调用getBean方法)都会创建一个bean的实例。
<bean id="SpringIocDao" class="ioc.dao.SpringIocDaoIpml" scope="prototype">

当Spring容器作用于不同的bean相互依赖时的问题
例如:一个作用域为prototype的dao的实现类注入 作用域为singleton的service中

    <bean id="SpringIocDao" class="ioc.dao.SpringIocDaoIpml" scope="prototype">
    </bean>
    <bean id="SpringIocService" class="ioc.service.SpringIocService" init-method="init" destroy-method="destroy">
        <constructor-arg name="springIocDao" ref="SpringIocDao"></constructor-arg>
        <constructor-arg name="str" value="zpp"></constructor-arg>
        <!--<property name="springIocDao" ref="SpringIocDao"></property>-->
    </bean>
//servicetest
        SpringIocService springIocService= (SpringIocService) ctx.getBean("SpringIocService");
        SpringIocService springIocService2= (SpringIocService) ctx.getBean("SpringIocService");

在第一次调用 ctx.getBean("SpringIocService")时,会产生一个SpringIocService的实例,通过依赖注入创建dao的实例,再将SpringIocService的实例存放到单例缓存中。
第二次调用ctx.getBean("SpringIocService")时,通过依赖注入生成了新的dao的实例,但是由于SpringIocService是单例模式,会从缓存当中取出旧的数据,springIocService2中存的还是springIocService1中的数据,新的dao实例不会得到更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值