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 中使用
相关推荐
默 语3 小时前
MySQL中的数据去重,该用DISTINCT还是GROUP BY?
java·数据库·mysql·distinct·group by·1024程序员节·数据去重
oDeviloo5 小时前
新版IntelliJ IDEA个性化设置兼容老版习惯
java·ide·intellij-idea
一只小透明啊啊啊啊5 小时前
Java Web 开发的核心组件:Servlet, JSP,Filter,Listener
java·前端·servlet
spencer_tseng6 小时前
Eclipse Uninstall Software
java·ide·eclipse
嗯、.6 小时前
使用 iText 9 为 PDF 添加文字水印的完整实战
java·pdf·itext
怪兽20147 小时前
缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题
java·缓存·面试
皮皮林5517 小时前
Java 25 正式发布:更简洁、更高效、更现代!
java
源码_V_saaskw7 小时前
JAVA国际版二手交易系统手机回收好物回收发布闲置商品系统源码支持APP+H5
java·开发语言·微信·智能手机·微信小程序·小程序
جيون داد ناالام ميづ7 小时前
Spring AOP核心原理分析
java·数据库·spring
霸道流氓气质7 小时前
SpringBoot+MybatisPlus+自定义注解+切面实现水平数据隔离功能(附代码下载)
java·spring boot·后端