最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring?bean標簽中的init-method和destroy-method詳解

 更新時間:2023年04月15日 11:38:58   作者:amcomputer  
這篇文章主要介紹了spring?bean標簽中的init-method和destroy-method,在很多項目中,經(jīng)常在xml配置文件中看到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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

景东| 青铜峡市| 霍州市| 平定县| 阳春市| 那坡县| 祁阳县| 项城市| 厦门市| 潞城市| 海丰县| 蓝田县| 沧源| 从江县| 福清市| 科技| 沂南县| 廊坊市| 金堂县| 博客| 锦州市| 田阳县| 张家界市| 庐江县| 武功县| 额尔古纳市| 阜平县| 盘锦市| 错那县| 元江| 都江堰市| 苗栗市| 社旗县| 金乡县| 潮安县| 江川县| 志丹县| 淮安市| 泰和县| 永修县| 道孚县|