Spring框架支持六個作用域,其中四個只有在Web中才能用到,在此我們只說明前兩種作用域,
下面是所有的六種作用域:
| Scope | Description |
|---|---|
|
singleton |
(Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
|
prototype |
Scopes a single bean definition to any number of object instances. |
|
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 bean definition. Only valid in the context of a web-aware Spring . |
|
session |
Scopes a single bean definition to the lifecycle of an HTTP . Only valid in the context of a web-aware Spring . |
|
application |
Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring . |
|
websocket |
Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring . |
這里我們對前兩種singleton(單例)和prototype(原型進行學習),
一、singleton
單例作用域是Spring框架的默認作用域,官方對它的說明是這樣的:
僅管理單例 Bean 的一個共享實體,并且所有對 ID 或 ID 與該 Bean 定義匹配的 Bean 的請求都會導致 Spring 容器回傳該特定 Bean 實體,
換句話說,當你定義一個bean定義并且它的范圍是一個單例時,Spring IoC容器只創建由該bean定義定義的物件的一個實體,此單個實體存盤在此類單例 Bean 的快取中,并且對該
命名 Bean 的所有后續請求和參考都將回傳快取的物件,下圖顯示了單例作用域的作業原理:

下面是官方給出的單例的實體:
<bean id="accountService" class="com.something.DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
上面兩段代碼的效果是完全一樣的,由于默認是單例模式,所以scope="singleton"這樣顯性地展示出來并非必要的,
下面我們對單例模式進行一個測驗,看它是否是同一個物件的實體,
<bean id="student" class="com.jms.pojo.Student">

由此我們可以確認這是同一個實體,
二、prototype
Bean 部署的非單例原型范圍會導致每次對特定 Bean 發出請求時都會創建新的 Bean 實體,也就是說,將 Bean 注入到另一個 Bean 中,或者您通過容器上的方法呼叫來請求它,通常,應將原型作用域用于所有有狀態 Bean,將單例作用域用于無狀態 Bean,

下面是官方給出的原型作用域的實體:
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
我們接下來對原型作用域進行測驗:
<bean id="student" class="com.jms.pojo.Student" scope="prototype">

可以看到使用原型作用域后兩個物件不再是一個實體,
(本文僅作個人學習記錄用,如有紕漏敬請指正)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/509404.html
標籤:Java
上一篇:佇列的模擬及環形佇列思路
下一篇:springcloud快速入門
