Bean的作用域

Bean的作用域

您不仅可以控制要插入到从特定bean定义创建的对象中的各种依赖项和配置值,还可以控制从特定bean定义创建的对象的范围。这种方法功能强大且灵活,因为您可以选择通过配置创建的对象的范围,而不必在Java类级别上烘烤对象的范围。可以将Bean定义为部署在多个范围之一中。Spring框架支持六个范围,其中只有在使用网络感知的情况下才能使用其中四个ApplicationContext。您还可以创建 自定义范围。

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
范围描述
单例(默认值)将每个Spring IoC容器的单个bean定义范围限定为单个对象实例。
原型将单个bean定义的作用域限定为任意数量的对象实例。
request将单个bean定义的范围限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有一个在单个bean定义的后面创建的bean实例。仅在可感知网络的Spring上下文中有效ApplicationContext
session将单个bean定义的范围限定为HTTP的生命周期Session。仅在可感知网络的Spring上下文中有效ApplicationContext
application将单个bean定义的作用域限定为的生命周期ServletContext。仅在可感知网络的Spring上下文中有效ApplicationContext
websocket将单个bean定义的作用域限定为的生命周期WebSocket。仅在可感知网络的Spring上下文中有效ApplicationContext

单例模式 spring默认机制

<bean id="address" class="com.liu.pojo.Address" scope="singleton">
    <property name="address" value="沈阳"></property>
</bean>

通过容器创建的所有对象,都是同一个对象(内存完全相同)

public class SpringTest {
    @Test
    public void Test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       /* Student student = (Student)context.getBean("student");
        System.out.println(student.toString());*/
        Address address = (Address) context.getBean("address");
        Address address1 = (Address) context.getBean("address");
        if(address==address1) {
            System.out.println(true);
        }
    }
}
//true

原型模式 创建的所有对象都不一样 ( 每次getBean都会产生新对象)

<bean id="address" class="com.liu.pojo.Address" scope="prototype">
    <property name="address" value="沈阳"></property>
</bean>
//测试代码返回 false

request、session、application、websocket

只能在web中使用

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值