Spring中 Bean 的六种作用域官方说明

 在 Spring 中有6种 Bean 作用域,分别为:

    1、singleton(单例作用域)

    2、prototype(原型作用域)

    3、request(请求作用域)

    4、session(会话作用域)

    5、application(全局作用域)

    6、websocket(HTTP WebSocket 作用域

下面展示这六种作用域的官方说明和使用场景等信息

1、singleton(单例作用域)

  • 官方说明:(Default)Scopes a single bean definition to a single object instance for each Spring IoC container.
  • 描述:该作用域下的 Bean 在Ioc容器中只存在一个实例,即 获取 Bean (通过 applicationContext.getBean 等方法获取)和 装配 Bean (通过 @Autowired 注入)都是同一个对象。
  • 场景:通过无状态的 Bean 使用该作用域。(无状态:表示 Bean 对象的属性状态不需要更新)
  • 备注:Spring 默认选择该作用域(性能最优)

2、prototype(原型作用域)

  • 官方说明:Scopes a single bean definition to any number of object instances.
  • 描述:每次对该作用域下的 Bean 的请求都会创建新的实例,即 获取 Bean (通过 applicationContext.getBean 等方法获取)和 装配 Bean (通过 @Autowired 注入)都是新的对象。
  • 场景:通常有状态的 Bean 使用该作用域

3、request(请求作用域)

  •  官方说明:Scopes 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.
  • 描述:每次 http 请求会创建新的 Bean 实例,类似于 prototype
  • 场景:一次 http 的请求和响应的共享同一个 Bean
  • 备注:限定 SpringMVC 中使用

4、session(会话作用域)

  • 官方说明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  • 描述:在一个 http session 中,定义一个 Bean 实例
  • 场景:用户会话共享同一个 Bean(例如记录一个用户的登陆信息)
  • 备注:限定 SpringMVC 中使用

5、application(全局作用域)

  •  官方说明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  • 描述:在一个 http servlet Context 中,定义一个 Bean 实例
  • 场景:Web 应用的上下文信息(例如记录一个应用的共享信息)
  • 备注: 限定 SpringMVC 中使用

 单例作用域(singleton)和 全局作用域(application)对比:

1. singleton 是 Spring Core 的作用域;application 是 Spring Web 中的作用域; 

2. singleton 作用于 IoC 的容器,而 application 作用于 Servlet 容器。

6、websocket(HTTP WebSocket 作用域)

  •  官方说明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  • 描述:在一个 HTTP WebSocket 的生命周期中,定义一个 Bean 实例。
  • 场景:WebSocket 的每次会话中,都保存一个 Map 结构的头信息,将用来包裹客户端信息头。第一次初始化后,直到 WebSocket 结束都是同一个 Bean。
  • 备注: 限定 Spring WebSocket 中使用
  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱躺平的威威

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值