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

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

1、singleton(单例作用域)

2、prototype(原型作用域)

3、request(请求作用域)

4、session(会话作用域)

5、application(全局作用域)

[6、websocket(HTTP WebSocket 作用域](#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 中使用
相关推荐
毕设源码-邱学长1 天前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
兑生1 天前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
daidaidaiyu1 天前
一文学习 Spring 声明式事务源码全流程总结
java·spring
零雲1 天前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
左左右右左右摇晃1 天前
Java并发——synchronized锁
java·开发语言
sxlishaobin1 天前
Java I/O 模型详解:BIO、NIO、AIO
java·开发语言·nio
彭于晏Yan1 天前
Spring AI(二):入门使用
java·spring boot·spring·ai
有一个好名字1 天前
vibe codeing 开发流程
java
兑生1 天前
【灵神题单·贪心】3745. 三元素表达式的最大值 | 排序贪心 | Java
java·开发语言
polaris06301 天前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat