詳解SpringIOC容器中bean的作用范圍和生命周期
bean的作用范圍:
可以通過scope屬性進行設置:
- singleton 單例的(默認)
- prototype 多例的
- request 作用于web應用的請求范圍
- session 作用于web應用的會話范圍
- global-session 作用于集群環(huán)境的會話范圍(全局會話范圍)
測試:
<!-- 默認是單例的(singleton)--> <bean id="human" class="com.entity.Human"></bean>
<bean id="human" class="com.entity.Human" scope="singleton"></bean>
@Test
public void test(){
//通過ClassPathXmlApplicationContext對象加載配置文件方式將javabean對象交給spring來管理
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//獲取Spring容器中的bean對象,通過id和類字節(jié)碼來獲取
Human human = applicationContext.getBean("human", Human.class);
Human human1 = applicationContext.getBean("human", Human.class);
System.out.println(human==human1);
}
結(jié)果:

將scope屬性設置為prototype時
<bean id="human" class="com.entity.Human" scope="prototype"></bean>
結(jié)果:

singleton和prototype的區(qū)別
- 如果bean屬性設置為singleton時,當我們加載配置文件時對象已經(jīng)被初始化
- 而如果使用prototype時,對象的創(chuàng)建是我們什么時候獲取bean時什么時候創(chuàng)建對象
當設置為prototype時


當設置為singleton時

bean對象的生命周期
單例對象:
- 出生:當容器創(chuàng)建時對象出生
- 活著:只有容器還在,對象一直活著
- 死亡:容器銷戶,對象死亡
- 單例對象和容器生命周期相同
測試:
先設置屬性init-method和destroy-method,同時在person類中寫入兩個方法進行輸出打印
public void init(){
System.out.println("初始化...");
}
public void destroy(){
System.out.println("銷毀了...");
}
<bean id="person" class="com.entity.Person" scope="singleton" init-method="init" destroy-method="destroy"> </bean>
測試類:
@Test
public void test(){
//通過ClassPathXmlApplicationContext對象加載配置文件方式將javabean對象交給spring來管理
ClassPathXmlApplicationContext Context=new ClassPathXmlApplicationContext("bean.xml");
// //獲取Spring容器中的bean對象,通過id和類字節(jié)碼來獲取
Person person = Context.getBean("person", Person.class);
//銷毀容器
Context.close();
}
結(jié)果:

總結(jié):單例對象和容器生命周期相同
當屬性改為prototype多例時
- 出生:當我們使用對象時spring框架為我們創(chuàng)建
- 活著:對象只要是在使用過程中就一直活著
- 死亡:當對象長時間不用,且沒有別的對象應用時,由java垃圾回收器回收對象
測試類:
@Test
public void test(){
//通過ClassPathXmlApplicationContext對象加載配置文件方式將javabean對象交給spring來管理
ClassPathXmlApplicationContext Context=new ClassPathXmlApplicationContext("bean.xml");
// //獲取Spring容器中的bean對象,通過id和類字節(jié)碼來獲取
Person person = Context.getBean("person", Person.class);
//銷毀容器
Context.close();
}
結(jié)果:

總結(jié):由于Spring容器不知道多例對象什么時候使用,什么時候能用完,只有我們自己知道,因此它不會輕易的把對象銷毀,它會通過java垃圾回收器回收對象
到此這篇關于SpringIOC容器中bean的作用范圍和生命周期的文章就介紹到這了,更多相關SpringIOC容器bean作用范圍和生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring-boot oauth2使用RestTemplate進行后臺自動登錄的實現(xiàn)
這篇文章主要介紹了Spring-boot oauth2使用RestTemplate進行后臺自動登錄的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07

