日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Spring (init-method和destroy-method )

系統(tǒng) 2184 0

轉自: http://www.blogjava.net/cmzy/archive/2008/07/29/218059.html

  1. /**
  2. *
  3. */
  4. package ioc.test;
  5. /**
  6. *@authorzhangyong
  7. *
  8. */
  9. public class Animal{
  10. private Stringname;
  11. private int age;
  12. public Stringspeak(){
  13. return "我的名字:" + this .name+ ",我的年齡:" + this .age;
  14. }
  15. public void init_xx() throws Exception{
  16. System.out.println( "初始化方法start()正在運行!" );
  17. }
  18. public void end() throws Exception{
  19. System.out.println( "析構方法end()正在運行!" );
  20. }
  21. //Geter和Seter省略
  22. }

配置文件中配置好bean,并為其指定響應的預處理方法和析構方法:

這里的init_xx方法在實例化與依賴注入之前被調用,end方法在銷毀之前調用

  1. <? xml version = "1.0" encoding = "UTF-8" ?>
  2. < beans
  3. xmlns = "http://www.springframework.org/schema/beans"
  4. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation ="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >
  7. < bean id = "animal" class = "ioc.test.Animal" init-method = "init_xx" destroy-method = "end" >
  8. < property name = "age" value = "5" > </ property >
  9. < property name = "name" value = "豬" > </ property >
  10. </ bean >
  11. </ beans >

創(chuàng)建含有主方法的測試類,代碼如下:

  1. /**
  2. *
  3. */
  4. package ioc.test;
  5. import org.springframework.context.support.AbstractApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7. /**
  8. *@authorzhangyong
  9. *
  10. */
  11. public class TestMain{
  12. public static void main(String[]args){
  13. AbstractApplicationContextac= new ClassPathXmlApplicationContext( "applicationContext.xml" );
  14. //注冊容器關閉鉤子,才能關掉容器,調用析構方法
  15. ac.registerShutdownHook();
  16. Animalanimal=ac.getBean( "animal", Animal.class );
  17. System.out.println(animal.speak());
  18. }
  19. }

運行主類,結果如下:


需要注意的是:要看到析構方法的輸出,也必須要注冊關閉鉤子。

Spring (init-method和destroy-method )


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 信宜市| 铜川市| 棋牌| 大同县| 固阳县| 芦溪县| 萍乡市| 穆棱市| 日照市| 尉犁县| 波密县| 璧山县| 富源县| 沧源| 历史| 乡城县| 英山县| 揭阳市| 涞水县| 大方县| 南丰县| 繁昌县| 长治市| 高密市| 蕲春县| 邢台市| 沛县| 喀什市| 隆德县| 清涧县| 万宁市| 嘉义县| 衡水市| 青田县| 于田县| 濮阳县| 渭南市| 潞城市| 马龙县| 汉川市| 泽库县|