Spring init-method和destroy-method属性的使用

来源:互联网 发布:淘宝的会员管理系统 编辑:程序博客网 时间:2024/05/17 05:14

Spring init-method和destroy-method属性的使用


有时候在bean初始化之后要执行的初始化方法,以及在bean销毁时执行的方法。这时就需要配置init-method
destroy-method属性,顾名思义,配置初始与销毁的方法。


操作步骤:
1、创建Speaker对象。

[java] view plain copy
 print?
  1. public class Speaker {  
  2.   
  3.     private String name;  
  4.     private String topic;  
  5.       
  6.     private Speaker(String name,String topic){  
  7.         this.name = name;  
  8.         this.topic = topic;  
  9.     }  
  10.       
  11.     /** 
  12.      * Speaker实例化时执行的方法 
  13.      */  
  14.     private void init() {  
  15.         System.out.println("执行Speaker 的 初始化方法 init");  
  16.     }  
  17.   
  18.     /** 
  19.      * Speaker销毁时执行的方法 
  20.      */  
  21.     private void destroy() {  
  22.         System.out.println("执行Speaker 的销毁方法 destroy");  
  23.     }  
  24.       
  25.     public void teach() {  
  26.           
  27.         System.out.println(toString());  
  28.     }  
  29.       
  30.     @Override  
  31.     public String toString() {  
  32.         return "Speaker [name=" + name + ", topic=" + topic + "]";  
  33.     }  
  34. }  

2、创建spring配置文件beanLearn05.xml。

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!-- Learn 05 init-method和destroy-method属性的使用 -->  
  8.     <bean id="speaker05" class="com.mahaochen.spring.learn05.Speaker"  
  9.         init-method="init" destroy-method="destroy">  
  10.         <constructor-arg index="0" value="elle" />  
  11.         <constructor-arg index="1" value="Study Hard!" />  
  12.     </bean>  
  13. </beans>  


3、将Spring配置文件beanLearn05.xml引入到主配置文件beans.xml中。

[html] view plain copy
 print?
  1. <!-- Learn 04  使用实例工厂方式实例化Bean -->  
  2.     <import resource="com/mahaochen/spring/learn05/beanLearn05.xml"/>  


4、编写测试类TestSpring05.Java。

[java] view plain copy
 print?
  1. public class TestSpring05 {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");  
  6.         Speaker speaker05 = (Speaker) appContext.getBean("speaker05");  
  7.         speaker05.teach();  
  8.         ((ClassPathXmlApplicationContext) appContext).close();  
  9.     }  
  10. }  
0 0
原创粉丝点击