2015-02-06 12:48

[轉載] Spring Bean Scope

轉載自:Spring Bean Scope 學習

在 Spring 中定義一個 Bean 時,可以針對其 scope 加以設定。在新版的 Spring 中,共有五種不同的 scope 可以設定,分別為:
singleton
在 Spring IoC Container,該 bean 只會有單一實例(a single instance),此為 Spring 預設值
prototype
在 Spring IoC Container 中,該 bean 可以有多個實例(any number of object instances)
request
在每一次的 HTTP Request,spring container 會根據 loginAction bean 的定義來建立一個全新的 instance,而且僅在目前的 request 中有效,所以可以放心的去更改 instance 的內部狀態,請求結束,request scope 的 bean instance 會被 destroy
session
針對某個 HTTP Session,spring container 會根據 userPreference bean 的定義來建立一個全新的 instance,同樣的,和 request scope 一樣,可以放心的去更改 instance 內部狀態。
global-session
僅在 portlet 為基礎的 Web 應用下有作用。Porlet 的規範中定義了 global session 的概念。


在定義 scope 時,會在 bean 中定義如下:
<bean id="helloWorld" class="HelloWorld" scope="singleton">

當 scope 設定為 singleton 時,整個 container 只會有一個 instance,所以下方的 obj 和 obj1 都會是同一個 instance。
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.setMessage("hello");
obj.getMessage();
HelloWorld obj1 = (HelloWorld) context.getBean("helloWorld");
obj1.getMessage();


<bean id="helloWorld" class="HelloWorld" scope="prototype">

如果設定為 prototype 時,obj 和 obj1 將會是不同的 instances,可以分別進行操作。在這裡,singleton 的單一 instance 是用 id 來進行識別,不同 id、相同 class 時,還是可以有多個 instances(getBean傳入不同的id即可)。


request、session 和 global-session 三種 scope 只能在 web 環境中使用,如果在非 web 環境設定,會出現【No Scope registered for scope 'request'】的錯誤。

0 回應: