2.Spring常用配置—1.Bean的Scope
1.點睛
Scope描述的是Spring容器如何新建Bean的實例的。Spring的Scope有以下幾種,通過@Scope注解來實現。
(1)Singleton:一個Spring容器中隻有一個Bean的實例,此為Spring的默認配置,全容器共享一個實例。
(2)Prototype:每次調用新建一個Bean的實例。
(3)Request:Web項目中,給每一個http request新建一個Bean實例。
(4)Session:Web項目中,給每一個http session新建一個Bean實例。
(5)GlobalSession:這個隻在portal應用中有用,給每一個global http session新建一個Bean實例。
另外,在Spring Batch中還有一個Scope是使用@StepScope,將在批處理一節介紹這個Scope。
本例簡單演示默認的Singleton和Prototype,分別從Spring容器中獲得2次Bean,判斷Bean的實例是否相等。
2.示例
(1)編寫Singleton的Bean
默認為Singleton,相當於@Scope("singleton")
(2)編寫Prototype的Bean
聲明Scope為Prototype
(3)配置類
(4)運行
結果:
最後更新:2017-04-26 22:30:46