Spring学习笔记:04 Bean的作用域 (Bean scopes)

1.单例模式(spring默认)

<bean id="user2" class="com.spring.people.User" c:name="1" c:age="99" scope="singleton"/>

此时如果在测试类中这样写

        ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
        User user = context.getBean("user2", User.class);
        User user2 = context.getBean("user2", User.class);
        System.out.println(user==user2);

此时运行将会输出true (user和user2其实是同一个对象)

下图为spring官方文档给出的示意图
spring

2.原型模式 每次从容器中getbean时都会产生新的对象

    <bean id="user2" class="com.spring.people.User" c:name="1" c:age="99" scope="prototype"/>

此时运行和上文相同的java代码输出为false
则user2与user地址不相同。为两个对象

下图为Spring官方对原型模式的解释
在这里插入图片描述

3.其余 request,session, application 这些只能在web开发中使用

 
 
 
 

补充:

多线程模式下尽量使用原型模式(prototype)其他情况尽量使用单例模式(singleton)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值