Bean的作用域

Bean的作用域

Bean 的作用域就是指bean的类型。

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默认选择该作用域

prototype

官方说明:Scopes a single bean definition to any number of object instances.
描述:每次对该作用域下的Bean的请求都会创建新的实例:获取Bean(即通过
applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注入)都是新的对象
实例。
场景:通常有状态的Bean使用该作用域
使用注解@Scope(“User”)实现、在User类的上方添加这样的注解、那么每次取User类的实例的时候、获取到的User 的对象就是不同的对象了。

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中使用

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中使用

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中使用

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中使用

上一篇:了解SPA-Single Page App


下一篇:single-spa5 + vue3 + ts微前端实践