spring?bean標簽中的init-method和destroy-method詳解
1 背景介紹
在很多項目中,經(jīng)常在xml配置文件中看到init-method 或者 destroy-method 。因此整理收集下,方便以后參考和學習??梢允褂?init-method 和 destroy-method 在bean 配置文件屬性用于在bean初始化和銷毀某些動作時。這是用來替代 InitializingBean和DisposableBean接口。
init-method 用于指定bean的初始化方法。 spring 容器會幫我們實例化對象,實例化對象之后,spring就會查找我們是否配置了init-method。如果在標簽配置了init-method,spring就會調(diào)用我們配置的init-method 方法,進行bean的初始化。需要注意的是,構建方法先執(zhí)行,執(zhí)行完后就會執(zhí)行 init-method 。
2 init-method
xml配置
<bean id="testService" class="com.test.TestService" init-method="myInit" destroy-method="myDestroy">
</bean>public class TestService {
public TestService(){
System.out.println("實例化:TestService");
}
public void myInit(){
System.out.println("初始化:TestService");
}
public void myDestroy(){
System.out.println("銷毀:TestService");
}
}測試
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
TestService cust = (CustomerService)context.getBean("testService");
System.out.println("hhhhh");
//context.close();
}
}輸出:
實例化:TestService
初始化:TestService
hhhhh
3 destroy-method
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
TestService cust = (CustomerService)context.getBean("testService");
System.out.println("hhhhh");
context.close();
}
}spring上下文關閉時候,才會進行銷毀。
輸出:
實例化:TestService
初始化:TestService
hhhhh
銷毀:TestService
4 總結
建議使用init-method 和 destroy-methodbean 在Bena配置文件,而不是執(zhí)行 InitializingBean 和 DisposableBean 接口,也會造成不必要的耦合代碼在Spring。
到此這篇關于spring bean標簽中的init-method和destroy-method的文章就介紹到這了,更多相關spring init-method和destroy-method內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解Java volatile 內(nèi)存屏障底層原理語義
為了保證內(nèi)存可見性,java 編譯器在生成指令序列的適當位置會插入內(nèi)存屏障指令來禁止特定類型的處理器重排序。為了實現(xiàn) volatile 內(nèi)存語義,JMM 會分別限制這兩種類型的重排序類型2021-09-09
解決java.util.NoSuchElementException異常的問題
這篇文章主要介紹了解決java.util.NoSuchElementException異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
java如何實現(xiàn)圖片轉(zhuǎn)化為數(shù)據(jù)流
這篇文章主要介紹了java如何實現(xiàn)圖片轉(zhuǎn)化為數(shù)據(jù)流,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
解決maven update project 后項目jdk變成1.5的問題
下面小編就為大家?guī)硪黄鉀Qmaven update project 后項目jdk變成1.5的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起 小編過來看看吧2016-11-11
Java編程之多線程死鎖與線程間通信簡單實現(xiàn)代碼
這篇文章主要介紹了Java編程之多線程死鎖與線程間通信簡單實現(xiàn)代碼,具有一定參考價值,需要的朋友可以了解下。2017-10-10
IDEA基于支付寶小程序搭建springboot項目的詳細步驟
這篇文章主要介紹了IDEA基于支付寶小程序搭建springboot項目的詳細步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
解決Mybatis 大數(shù)據(jù)量的批量insert問題
這篇文章主要介紹了解決Mybatis 大數(shù)據(jù)量的批量insert問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

