Spring (init-method和destroy-method )

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

代码    查看源代码 打印
  1. /** 
  2.  *  
  3.  */  
  4. package ioc.test;  
  5. /** 
  6.  * @author zhangyong 
  7.  *  
  8.  */  
  9. public class Animal{  
  10.      private String name;  
  11.      private int age;  
  12.          public String speak(){  
  13.          return "我的名字:"+this.name+",我的年龄:"+this.age;  
  14.      }  
  15.    
  16.      public void init_xx() throws Exception {  
  17.          System.out.println("初始化方法start()正在运行!");  
  18.      }  
  19.    
  20.      public void end() throws Exception {  
  21.          System.out.println("析构方法end()正在运行!");  
  22.      }  
  23.    
  24.  //Geter和Seter省略  
  25.    
  26. }  

        配置文件中配置好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.       
  8.     <bean id="animal" class="ioc.test.Animal" init-method="init_xx" destroy-method="end">  
  9.        <property name="age"  value="5"></property>  
  10.        <property name="name" value="猪"></property>  
  11.     </bean>  
  12.    
  13. </beans>  

         创建含有主方法的测试类,代码如下:

代码    查看源代码 打印
  1. /** 
  2.  *  
  3.  */  
  4. package ioc.test;  
  5.    
  6. import org.springframework.context.support.AbstractApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.    
  9. /** 
  10.  * @author zhangyong 
  11.  *  
  12.  */  
  13. public class TestMain {  
  14.    
  15.     public static void main(String[] args) {   
  16.            AbstractApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");  
  17.            
  18.                   //注册容器关闭钩子,才能关掉容器,调用析构方法  
  19.          ac.registerShutdownHook();  
  20.    
  21.          Animal animal =ac.getBean("animal",Animal.class);  
  22.    
  23.          System.out.println(animal.speak());  
  24.            
  25.      }      
  26. }  

         运行主类,结果如下:


需要注意的是:要看到析构方法的输出,也必须要注册关闭钩子。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值