Bean 作用域和生命周期
- 1. 作用域
- 1.1 作用域定義
- 1.2 Bean 的 6 種作?域
- 1.2.1 singleton(單例作?域)
- 1.2.2 prototype (原型作?域 / 多例作?域)
- 1.2.3 request:(請求作?域)
- 1.2.4 session:(會話作?域)
- 1.2.5 application:(全局作?域)
- 1.2.6 websocket:(HTTP WebSocket 作?域)
- 1.3 設置作用域
- 2. 生命周期
1. 作用域
1.1 作用域定義
Bean 的作?域是指 Bean 在 Spring 整個框架中的某種?為模式,?如 singleton 單例作?域,就表示 Bean 在整個 Spring 中只有?份,它是全局共享的,那么當其他?修改了這個值之后,那么另?個?讀取到的就是被修改的值。
1.2 Bean 的 6 種作?域
1.2.1 singleton(單例作?域)
- 官?說明:(Default) Scopes a single bean definition to a single object instance for eachSpring IoC container.
- 描述:該作?域下的Bean在IoC容器中只存在?個實例:獲取Bean(即通過applicationContext.getBean等?法獲取)及裝配Bean(即通過@Autowired注?)都是同?個對象。
- 場景:通常?狀態的Bean使?該作?域。?狀態表示Bean對象的屬性狀態不需要更新
- 備注:Spring默認選擇該作?域
1.2.2 prototype (原型作?域 / 多例作?域)
- 官?說明:Scopes a single bean definition to any number of object instances.
- 描述:每次對該作?域下的Bean的請求都會創建新的實例:獲取Bean(即通過applicationContext.getBean等?法獲取)及裝配Bean(即通過@Autowired注?)都是新的對象實例。(將原對象復制一份)
- 場景:通常有狀態的Bean使?該作?域
1.2.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 beandefinition. Only valid in the context of a web-aware Spring ApplicationContext.
- 描述:每次http請求會創建新的Bean實例,類似于prototype
- 場景:?次http的請求和響應的共享Bean
- 備注:限定SpringMVC中使?
1.2.4 session:(會話作?域)
- 官?說明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid inthe context of a web-aware Spring ApplicationContext.
- 描述:在?個http session中,定義?個Bean實例
- 場景:?戶回話的共享Bean, ?如:記錄?個?戶的登陸信息
- 備注:限定SpringMVC中使?
1.2.5 application:(全局作?域)
- 官?說明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid inthe context of a web-aware Spring ApplicationContext.
- 描述:在?個http servlet Context中,定義?個Bean實例
- 場景:Web應?的上下?信息,?如:記錄?個應?的共享信息
- 備注:限定SpringMVC中使?
1.2.6 websocket:(HTTP WebSocket 作?域)
- 官?說明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in thecontext of a web-aware Spring ApplicationContext.
- 描述:在?個HTTP WebSocket的?命周期中,定義?個Bean實例
- 場景:WebSocket的每次會話中,保存了?個Map結構的頭信息,將?來包裹客戶端消息頭。第?次初始化后,直到WebSocket結束都是同?個Bean。
- 備注:限定Spring WebSocket中使?
Spring 中只能使用前兩種
singleton 和 application 的區別:
- singleton 作?于 IoC 的容器,? application 作?于 Servlet 容器
- singleton 是 Spring Core 的作?域;application 是 Spring Web 中的作?域
1.3 設置作用域
使? @Scope 標簽就可以?來聲明 Bean 的作?域
@Scope 的參數可以有兩種方式:
- 直接在括號中聲明作用域類型, 例如: @Scope(“prototype”)
- 使用全家變量作為參數, 例如: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
2. 生命周期
所謂的?命周期指的是?個對象從誕?到銷毀的整個?命過程,我們把這個過程就叫做?個對象的?命周期。
Bean 的?命周期分為以下 5 ?部分:
1.實例化 Bean(為 Bean 分配內存空間)
2.設置屬性(Bean 注?和裝配)
3.Bean 初始化
- 實現了各種 Aware 通知的?法,如 BeanNameAware、 BeanFactoryAware、ApplicationContextAware 的接??法;
- 執? BeanPostProcessor 初始化前置?法;
- 執? @PostConstruct 初始化?法,依賴注?操作之后被執?;
- 執???指定的 init-method ?法(如果有指定的話);
- 執? BeanPostProcessor 初始化后置?法。
4.使? Bean
5.銷毀 Bean
實例化和初始化的區別:
實例化和屬性設置是 Java 級別的系統“事件”,其操作過程不可???預和修改;?初始化是給開發者提供的,可以在實例化之后,類加載完成之前進??定義“事件”處理。