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

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

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

[java] view plain copy
 
  1. public class Speaker {  
  2.   
  3.     private Speaker(){  
  4.     system.out.println("执行了构造方法");
  5.     }  
  6.       
  7.     /** 
  8.      * Speaker实例化时执行的方法 
  9.      */  
  10.     private void init() {  
  11.         System.out.println("执行Speaker 的 初始化方法 init");  
  12.     }  
  13.   
  14.     /** 
  15.      * Speaker销毁时执行的方法 
  16.      */  
  17.     private void destroy() {  
  18.         System.out.println("执行Speaker 的销毁方法 destroy");  
  19.     }  
  20.       
  21.     public void teach() {  
  22.         System.out.println(toString(“-----------------------------------”));  
  23.     }  
  24. }  

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

[html] view plain copy
 
  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.     </bean>  
  11. </beans>  


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

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

4、编写测试类TestSpring05.java。

[java] view plain copy
 
    1. public class TestSpring05 {  
    2. public static void main(String[] args) {  
    3.         ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");  
    4.         Speaker speaker05 = (Speaker) appContext.getBean("speaker05");  
    5.         speaker05.teach();  
    6.         ((ClassPathXmlApplicationContext) appContext).close();  
    7.     }
    8. }  

输出结果

执行了构造方法

执行Speaker 的 初始化方法 init

-----------------------------------

执行Speaker 的销毁方法 destroy

说明:

在执行完毕后需要将((ClassPathXmlApplicationContext) context).close();Close关闭才可执行destroy-method

原文地址:https://www.cnblogs.com/hzdzkjdxygz/p/8144579.html