bean的作用范圍:
可以通過scope屬性進行設置:
- singleton 單例的(默認)
- prototype 多例的
- request 作用于web應用的請求范圍
- session 作用于web應用的會話范圍
- global-session 作用于集群環境的會話范圍(全局會話范圍)
測試:
1
2
|
<!-- 默認是單例的(singleton)--> <bean id= "human" class = "com.entity.human" ></bean> |
1
|
<bean id= "human" class = "com.entity.human" scope= "singleton" ></bean> |
1
2
3
4
5
6
7
8
9
|
@test public void test(){ //通過classpathxmlapplicationcontext對象加載配置文件方式將javabean對象交給spring來管理 applicationcontext applicationcontext= new classpathxmlapplicationcontext( "bean.xml" ); //獲取spring容器中的bean對象,通過id和類字節碼來獲取 human human = applicationcontext.getbean( "human" , human. class ); human human1 = applicationcontext.getbean( "human" , human. class ); system.out.println(human==human1); } |
結果:
將scope屬性設置為prototype時
1
|
<bean id= "human" class = "com.entity.human" scope= "prototype" ></bean> |
結果:
singleton和prototype的區別
- 如果bean屬性設置為singleton時,當我們加載配置文件時對象已經被初始化
- 而如果使用prototype時,對象的創建是我們什么時候獲取bean時什么時候創建對象
當設置為prototype時
當設置為singleton時
bean對象的生命周期
單例對象:
- 出生:當容器創建時對象出生
- 活著:只有容器還在,對象一直活著
- 死亡:容器銷戶,對象死亡
- 單例對象和容器生命周期相同
測試:
先設置屬性init-method和destroy-method,同時在person類中寫入兩個方法進行輸出打印
1
2
3
4
5
6
7
|
public void init(){ system.out.println( "初始化..." ); } public void destroy(){ system.out.println( "銷毀了..." ); } |
1
2
3
|
<bean id= "person" class = "com.entity.person" scope= "singleton" init-method= "init" destroy-method= "destroy" > </bean> |
測試類:
1
2
3
4
5
6
7
8
9
|
@test public void test(){ //通過classpathxmlapplicationcontext對象加載配置文件方式將javabean對象交給spring來管理 classpathxmlapplicationcontext context= new classpathxmlapplicationcontext( "bean.xml" ); // //獲取spring容器中的bean對象,通過id和類字節碼來獲取 person person = context.getbean( "person" , person. class ); //銷毀容器 context.close(); } |
結果:
總結:單例對象和容器生命周期相同
當屬性改為prototype多例時
- 出生:當我們使用對象時spring框架為我們創建
- 活著:對象只要是在使用過程中就一直活著
- 死亡:當對象長時間不用,且沒有別的對象應用時,由java垃圾回收器回收對象
測試類:
1
2
3
4
5
6
7
8
9
|
@test public void test(){ //通過classpathxmlapplicationcontext對象加載配置文件方式將javabean對象交給spring來管理 classpathxmlapplicationcontext context= new classpathxmlapplicationcontext( "bean.xml" ); // //獲取spring容器中的bean對象,通過id和類字節碼來獲取 person person = context.getbean( "person" , person. class ); //銷毀容器 context.close(); } |
結果:
總結:由于spring容器不知道多例對象什么時候使用,什么時候能用完,只有我們自己知道,因此它不會輕易的把對象銷毀,它會通過java垃圾回收器回收對象
到此這篇關于springioc容器中bean的作用范圍和生命周期的文章就介紹到這了,更多相關springioc容器bean作用范圍和生命周期內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_45608165/article/details/113842753