一文搞懂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 class文件格式_動力節(jié)點Java學院整理
對于理解JVM和深入理解Java語言, 學習并了解class文件的格式都是必須要掌握的功課2017-06-06
Java并發(fā)編程中使用Executors類創(chuàng)建和管理線程的用法
這篇文章主要介紹了Java并發(fā)編程中使用Executors類創(chuàng)建和管理線程的用法,文中舉了用其啟動線程和設置線程優(yōu)先級的例子,需要的朋友可以參考下2016-03-03
詳解SpringCloud-Alibaba-Seata分布式事務
這篇文章主要介紹了SpringCloud-Alibaba-Seata分布式事務的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

