layout: post
author: zjhChester
header-img: img/post-bg-universe.jpg
catalog: true
tags:
- spring
bean對象的生命週期
1、單例對象:
出生:
當文件創建時對象出生(剛解析完配置文件)ApplicationContext
活着:
只要容器還在,對象一直活着
死亡:
容器銷燬,對象銷燬
總結:
單例對象生命週期與容器相同
測試:
第一步:
<!-- 指定bean對象銷燬和初始化的方法 -->
<!-- scope="singleton" 單例模式-->
<bean scope="singleton" id="Service" class="com.tfs.service.impl.ServiceImpl" init-method="init" destroy-method="destroy">
第二步:
//編寫對應bean對象的init destroy方法
public void init() {
System.out.println("對象初始化了");
}
public void destroy() {
System.out.println("對象銷燬了");
}
第三步:
編寫測試類:
//指定容器類型爲類類型,避免多態性導致無法關閉容器
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
Service service = ac.getBean("Service",Service.class);
service.say();
//手動銷燬
ac.close();
結果:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-yMQtLCJS-1580545987735)(/mdImg/bean%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.assets/1569730513921.png)]
2、多例對象:
<!--scope="prototype"多例對象 -->
<bean scope="prototype" id="Service" class="com.tfs.service.impl.ServiceImpl" init-method="init" destroy-method="destroy">
出生:
當我們使用對象時spring框架纔會創建
活着:
對象只要是在使用過程中就活着
死亡:
當對象長時間不用,且沒有別的對象引用時。由java的垃圾回收器GC回收