[spring]從頭開始-Bean Scopes

開發工具:IntelliJ IDEA 13

開發環境:jdk1.6.0_45

Framework:spring 3

先來簡單看一下一般的 spring-config.xml配置檔

    <bean id="inheritParent" class="foo.bar.SimpleBean" scope="signleton">

        <property name="name">

            <value>Clarence Ho</value>

        </property>

        <property name="age">

            <value>22</value>

        </property>

    </bean>

scope 可以解釋為 範圍,既該 bean 所要運行的範圍

一般 bean 預設的 scope 是 signleton 在配置 bean 時一般預設可以省略該一設定

但我們可以照我們的使用狀況,將其變更為我們想要使用的 scope

scope 有以下幾種(Reference. Pro Spring 3)

Scope type

description

Singleton

The default singleton scope.

Spring 預設的單例模式,每次Inject只會產生一個實體

Prototype

A new instance will be created by Spring when requested by application.

每次Inject(request)皆會產生一個新的實體

Request

For web application use. When using Spring MVC for web application,

beans with request scope will be instantiated for every HTTP request and then

destroyed when the request is completed.

使用在Web應用程式範圍中,在每次的Http Request 中產生,並於 Request Completed中 destory

Session

For web application use. When using Spring MVC for web applications,

beans with session scope will be instantiated for every HTTP session and then

destroyed when the session is over.

與Request中類似,同樣是使用在Web應用程式範圍中,實體產生在Http Session中,並於 Session is over 後 destory

Global

session:For portlet-based web applications. The global session scope beans

can be shared among all portlets withinthe same Spring MVC–powered portal

application.

Thread

A new bean instance will be created by Spring when requested by a new

thread, while for the same thread, the same bean instance will be returned. Note

that this scope is not registered by default.

使用在 Thread(執行緒) 中,同一個Thread 會有相同的實體

Custom

Custom bean scope that can be created by implementing the interface

org.springframework.beans.factory.config.Scope and registering the custom

scope in Spring’s configuration (for XML, use the class org.springframework.beans

.factory.config.CustomScopeConfigurer).

自訂的 Scope,藉由implement org.springframework.beans.factory.config.Scope 來完成