spring?bean標(biāo)簽中的init-method和destroy-method詳解
1 背景介紹
在很多項(xiàng)目中,經(jīng)常在xml配置文件中看到init-method 或者 destroy-method 。因此整理收集下,方便以后參考和學(xué)習(xí)??梢允褂?init-method 和 destroy-method 在bean 配置文件屬性用于在bean初始化和銷毀某些動作時。這是用來替代 InitializingBean和DisposableBean接口。
init-method 用于指定bean的初始化方法。 spring 容器會幫我們實(shí)例化對象,實(shí)例化對象之后,spring就會查找我們是否配置了init-method。如果在標(biāo)簽配置了init-method,spring就會調(diào)用我們配置的init-method 方法,進(jìn)行bean的初始化。需要注意的是,構(gòu)建方法先執(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("實(shí)例化: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();
}
}輸出:
實(shí)例化: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上下文關(guān)閉時候,才會進(jìn)行銷毀。
輸出:
實(shí)例化:TestService
初始化:TestService
hhhhh
銷毀:TestService
4 總結(jié)
建議使用init-method 和 destroy-methodbean 在Bena配置文件,而不是執(zhí)行 InitializingBean 和 DisposableBean 接口,也會造成不必要的耦合代碼在Spring。
到此這篇關(guān)于spring bean標(biāo)簽中的init-method和destroy-method的文章就介紹到這了,更多相關(guān)spring init-method和destroy-method內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot聲明式事務(wù)的簡單運(yùn)用說明
這篇文章主要介紹了SpringBoot聲明式事務(wù)的簡單運(yùn)用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
java網(wǎng)絡(luò)爬蟲連接超時解決實(shí)例代碼
這篇文章主要介紹了java網(wǎng)絡(luò)爬蟲連接超時解決的問題,分享了一則使用httpclient解決連接超時的Java爬蟲實(shí)例代碼,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Springboot @Validated和@Valid的區(qū)別及使用詳解
這篇文章主要介紹了Springboot @Validated和@Valid的區(qū)別及使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
maven創(chuàng)建spark項(xiàng)目的pom.xml文件配置demo
這篇文章主要為大家介紹了maven創(chuàng)建spark項(xiàng)目的pom.xml文件配置demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
Java如何實(shí)現(xiàn)圖片裁剪預(yù)覽功能
通常注冊賬戶上傳用戶圖像時需要進(jìn)行預(yù)覽,這篇文章就是教我們?nèi)绾斡?Java 實(shí)現(xiàn)圖片裁剪預(yù)覽功能,需要的朋友可以參考下2015-07-07
Java實(shí)現(xiàn)鎖定某個變量的幾種方式示例詳解
這篇文章主要為大家介紹了Java實(shí)現(xiàn)鎖某個變量的幾種方式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09

