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

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实例不会得到更新。


版权声明:本文为Advance_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。