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

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. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值