溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring?bean標(biāo)簽中的init-method和destroy-method怎么使用

發(fā)布時(shí)間:2023-04-15 13:55:41 來源:億速云 閱讀:92 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了spring bean標(biāo)簽中的init-method和destroy-method怎么使用的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇spring bean標(biāo)簽中的init-method和destroy-method怎么使用文章都會(huì)有所收獲,下面我們一起來看看吧。

1 背景介紹

在很多項(xiàng)目中,經(jīng)常在xml配置文件中看到init-method 或者 destroy-method 。因此整理收集下,方便以后參考和學(xué)習(xí)??梢允褂?init-method 和 destroy-method 在bean 配置文件屬性用于在bean初始化和銷毀某些動(dòng)作時(shí)。這是用來替代 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

關(guān)于“spring bean標(biāo)簽中的init-method和destroy-method怎么使用”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“spring bean標(biāo)簽中的init-method和destroy-method怎么使用”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI