2014年4月1日 星期二

Spring Bean Scopes

在spring的配置文件中,

除了對bean作屬性和依賴關係的配置外,

另一個部分便是作用範圍的設定,

下面列出五個可以選擇的範圍 ( Spring 2.0之後 ):

singleton

在springIoC容器中只會有一個bean實例,

spring的ApplicationContext容器在啟動時,

會自動實例化所有singleton的bean緩存在容器中,

由於spring利用AOP及LocalThread的功能進行singleton的處理,

因此非線程安全的設置為singleton後也會是線程安全的,

所以spring中默認的作用域便是singleton,

如果不想在一開始就進行實例化,

可以在bean的後面加上lazy-init="true",

但如果你的bean被其他設定為singleton的bean所使用到,

那就算設定lazy-init="true",

該bean也會在一開始就被實例化。

prototype

當你的scope設定為prototype後,

每次呼叫bean都會產生一個新的bean回傳,

類似java程式中所寫的 new XXObject() 一樣,

默認情況spring啟動不會實例化prototype的bean,

並且在被呼叫之後,

spring便不會去處理bean的生命週期了,

由呼叫者自行處理。

另外三個與web application 相關的範圍設定,

在使用之前必須先到web.xml中進行配置,

<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>

request

設定為request的bean,

當HTTP請求呼叫時實例該bean,

生命週期也隨HTTP請求結束而destroy()。

session

作用域包含整個HTTP session,

該session中呼叫的都是同一個實例化的bean,

session中所有的請求都用同一個bean,

隨HTTP session結束而destroy()。

globalSession

只在Portlet的web application中使用,

被所有portlet web組成的子portlet所使用。

沒有留言:

張貼留言