Bean的作用域
- Singleton
- prototype
- request
- session
- application
- websocket
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中使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/291628.html
標籤:java
