Spring Bean的作用域

bean的范围由<bean>的scope属性决定,可选值:singleton、request、session、websocket、application,默认singleton

The scope of this bean: typically “singleton” (one shared instance, which will be returned by all calls to getBean with the given id), or “prototype” (independent instance resulting from each call to getBean). By default, a bean will be a singleton, unless the bean has a parent bean definition in which case it will inherit the parent’s scope. Singletons are most commonly used, and are ideal for multi-threaded service objects. Further scopes, such as “request” or “session”, might be supported by extended bean factories (e.g. in a web environment). Inner bean definitions inherit the scope of their containing bean definition, unless explicitly specified: The inner bean will be a singleton if the containing bean is a singleton, and a prototype if the containing bean is a prototype, etc.

bean的scope属性:典型的是singleton(一个共享的实例,所有针对该bean的调用都返回该实例),或者prototype(每次调用返回一个新实例)。默认是singleton,除非父bean已经定义了一个scope值,这样则会继承该值。singleton是最常用的,而且在多线程服务中是比较适合的。内部类继承外部类的scope属性值,除非特别指定

【singleton】

singleton范围bean实例的范围仅限于Spring容器实例,在多个容器中也不是单例的

在默认情况下,singleton范围的bean是预先实例化的,这意味着在创建Spring容器实例的时候,将会创建singleton范围bean的实例。

  • 可以通过设置init-lazy="true"来让singleton范围的bean延迟初始化,当第一次请求的时候才创建bean实例
  • 也可以通过使用<beans>default-lazy-init来指定程序上下文中bean的默认策略,当与bean自己策略冲突时,会采用bean自己的策略
  • 在大多数场景中,创建容器的时候就初始化实例有助于及早发现配置问题

【prototype】

每次调用都会返回一个新实例。prototype的bean总是延迟初始化

如果一个bean不会保持任何会话状态(也就是说它是无状态的),那么它应该定义为一个singleton。
如果一个bean保持会话状态,它应该定义一个prototype。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值