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. }  

         运行主类,结果如下:


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

你可能感兴趣的:(spring,bean,String,测试,encoding)