spring 單例模式

2021-06-18 16:53:37 字數 946 閱讀 3704

單例模式,在spring 中其實是scope(作用範圍)引數的預設設定值

每個bean定義只生成乙個物件例項,每次getbean請求獲得的都是此例項

餓漢模式

spring singleton的預設是餓漢模式:啟動容器時(即例項化容器時),為所有spring配置檔案中定義的bean都生成乙個例項

懶漢模式

在第乙個請求時才生成乙個例項,以後的請求都呼叫這個例項

spring singleton設定為懶漢模式:

呼叫getbean時,就new乙個新例項

singleton

xml配置檔案:

測試**:

ontext("spring-hibernate-mysql.xml");

***typedao tdao1 = (***typedao)ctx.getbean("***typedao");

***typedao tdao2 = (***typedao)ctx.getbean("***typedao");

執行: 

true

com.machome.hibernate.impl.***typedaoimpl@15b0333

com.machome.hibernate.impl.***typedaoimpl@15b0333

說明前後兩次getbean()獲得的是同一例項,說明spring預設是單例

prototype

scope="prototype" />

執行同樣的測試**

執行:false

com.machome.hibernate.impl.***typedaoimpl@afae4a

com.machome.hibernate.impl.***typedaoimpl@1db9852

說明scope="prototype"後,每次getbean()的都是不同的新例項

Spring 單例模式

jvm的工作原理 a 類載入器 通過類載入器將編譯好的位元組碼檔案載入到jvm中。b 位元組碼校驗器 校驗載入過來的位元組碼的合法,如是否損壞或者被病毒篡改過等。如果校驗失敗則不會繼續執行了。c 直譯器 解釋執行位元組碼生成目標平台的機器碼執行。靜態成員在什麼時候就存在了?在位元組碼檔案被成功載入到...

Spring 單例模式

spring物件預設是單例的。可以通過scope屬性更改為多例。通過配置檔案 bean id test class test.test scope prototype bean 通過註解 controller scope prototype public class testcontroller 理...

Spring 單例模式和多例模式

singleton 單例 只有乙個共享的例項存在,所有對這個bean的請求都會返回這個唯一的例項。prototype 多例 對這個bean的每次請求都會建立乙個新的bean例項,類似於new。spring bean 預設是單例模式。單例測試 測試類user user1 user context.ge...