Spring Bean-Scopes作用域-Singleton单例模式、ProtoType原型模式

Bean-Scopes作用域

image-20200821221256695

image-20200821221402150

  • Singleton 单例
  • Prototype 原型
  • request 请求
  • session 会话
  • application 应用
  • WebSocket 连接

主要使用前两种

Singleton 单例模式

单例模式是Spring的默认机制

只管理Singleton bean 的一个共享实例,带有一个或多个match bean定义的id到导致只返回一个特定的bean实例

定义的bean限定为singleton时,只创建该bean定义的object的一个实例,存储在singleton缓存中,后续的请求都引用缓存中的实例

image-20200821223016035

只创建一个实例
这个共享实例被共享到每个协作对象中

Spring中的singleton bean概念于singleton pettern的概念不同,如果在单个 Spring 容器中为特定 class 定义一个 bean,则 Spring 容器将创建该_ bean 定义所定义的 class 的一个且仅一个实例。

<bean id="accountService" class="com.something.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

Demo

  • <bean id="studentTest" class="com.haoyun.POJO.Student" >
        <property name="address" ref="address"/>
    </bean>
    <bean id="studentTest2" class="com.haoyun.POJO.Student" >
        <property name="address" ref="address"/>
    </bean>
    <bean id="address" class="com.haoyun.POJO.Address" p:address="address" scope="singleton" />
    
  • address是单例模式的,根据单例模式的性质,应该值会创建一个实例,那只创建一个实例,那些被创建的实例中的address成员使用的应该是同一个引用

  • @Test
    public void BeanTest(){
        ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student studentTest = (Student) classPathXmlApplicationContext.getBean("studentTest");
        Student studentTest2 = (Student) classPathXmlApplicationContext.getBean("studentTest2");
        System.out.println(studentTest);
        System.out.println(studentTest2);
        System.out.println(studentTest == studentTest2);
        System.out.println(studentTest.getAddress() == studentTest2.getAddress());
    }
    
  • image-20200821225802113

  • 得出的结果是两个对象是不同的,但是address是同一个对象,使用同一个reference

ProtoType 原型模式

bean部署的不是单例模式的原型范围都会创建一个新的bean实例,并对该特定bean发出请求,

image-20200821231231713

每个bean都是一个单独的对象

配置和组装object交给client,client code必须清理prototype-scoped object释放原型beans所拥有的昂贵资源,之后可以尝试自定义bean post-processor,释放资源

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

每次从容器中get的时候都会产生一个新的对象

其余的request,session,application,这些只能在web开发中使用到,自行理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值