一文搞懂Spring中Bean的生命周期
生命周期:從創(chuàng)建到消亡的完整過程
bean聲明周期:bean從創(chuàng)建到銷毀的整體過程
bean聲明周期控制:在bean創(chuàng)建后到銷毀前做一些事情
一、使用配置生命周期的方法
在BookDaoImpl中實現(xiàn)類中創(chuàng)建相應的方法:
//表示bean初始化對應的操作
public void init(){
System.out.println("init...");
}
//表示bean銷毀前對應的操作
public void destory(){
System.out.println("destory...");
}
applicationContext.xml配置初始化聲明周期回調函數(shù)及銷毀聲明周期回調函數(shù)
<!--init-method:設置bean初始化生命周期回調函數(shù)-->
<!--destroy-method:設置bean銷毀生命周期回調函數(shù),僅適用于單例對象-->
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
執(zhí)行結果:

虛擬機退出,沒有給bean銷毀的機會。
可利用ClassPathXmlApplictionContext里的close方法主動關閉容器,就會執(zhí)行銷毀方法。
import com.itheima.dao.BookDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppForLifeCycle {
public static void main( String[] args ) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
//關閉容器
ctx.close();
}
}
執(zhí)行結果:

不過這種方式比較暴力,容器還提供另外的方法
在AppForLifeCycle中用關閉鉤子函數(shù)
//注冊關閉鉤子函數(shù),在虛擬機退出之前回調此函數(shù),關閉容器
ctx.registerShutdownHook();
執(zhí)行結果:

關閉鉤子在任何時間都可以執(zhí)行,close關閉比較暴力。
二、生命周期控制——接口控制(了解)
applicationContext.xml配置:
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
</bean>
BookServiceImpl:
可以利用接口InitializingBean和DisposableBean來設置初始化和銷毀后的方法設置
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set .....");
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
public void destroy() throws Exception {
System.out.println("service destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("service init");
}
}
執(zhí)行結果:

可以看出set在執(zhí)行在init的執(zhí)行之后,當你的屬性設置完以后,才去執(zhí)行afterPropertiesSet,所有才叫afterPropertiesSet,在屬性設置之后。
小結
生命周期總結
初始化容器
- 1、創(chuàng)建對象
- 2、執(zhí)行構造方法
- 3、執(zhí)行屬性注入(set操作)
- 4、執(zhí)行bean初始化方法
使用bean
執(zhí)行業(yè)務操作
關閉/銷毀容器
執(zhí)行bean操作
1、bean生命周期控制
配置
init-method
destroy-method
接口(了解)
InitializingBean
DisposableBean
2、關閉容器
ConfigurableApplicationContext
close()
registerShutdownHook()
到此這篇關于一文搞懂Spring中Bean的生命周期的文章就介紹到這了,更多相關Spring Bean生命周期內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java?HttpURLConnection使用方法與實例演示分析
這篇文章主要介紹了Java?HttpURLConnection使用方法與實例演示,HttpURLConnection一個抽象類是標準的JAVA接口,該類位于java.net包中,它提供了基本的URL請求,響應等功能,下面我們來深入看看2023-10-10
Java更新調度器(update scheduler)的使用詳解
Java更新調度器是Java中的一個特性,可以自動化Java應用程序的更新過程,它提供了一種方便的方式來安排Java應用程序的更新,確保其與最新的功能、錯誤修復和安全補丁保持同步,本文將深入介紹如何使用Java更新調度器,并解釋它對Java開發(fā)人員和用戶的好處2023-11-11

