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