您好,登錄后才能下訂單哦!
這篇文章主要介紹了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ì)有所收獲,下面我們一起來看看吧。
在很多項(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 。
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
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è)資訊頻道。
免責(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)容。