首页 > 编程语言 > 详细

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

时间:2014-12-26 21:41:46      阅读:360      评论:0      收藏:0      [点我收藏+]

知识点介绍:
有时候在bean初始化之后要执行的初始化方法,以及在bean销毁时执行的方法。这时就需要配置init-method和destroy-method属性,顾名思义,配置初始与销毁的方法。
【转载使用,请注明出处:http://blog.csdn.net/mahoking


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

public class Speaker {

	private String name;
	private String topic;
	
	private Speaker(String name,String topic){
		this.name = name;
		this.topic = topic;
	}
	
	/**
	 * Speaker实例化时执行的方法
	 */
	private void init() {
		System.out.println("执行Speaker 的 初始化方法 init");
	}

	/**
	 * Speaker销毁时执行的方法
	 */
	private void destroy() {
		System.out.println("执行Speaker 的销毁方法 destroy");
	}
	
	public void teach() {
		
		System.out.println(toString());
	}
	
	@Override
	public String toString() {
		return "Speaker [name=" + name + ", topic=" + topic + "]";
	}
}

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- Learn 05 init-method和destroy-method属性的使用 -->
	<bean id="speaker05" class="com.mahaochen.spring.learn05.Speaker"
		init-method="init" destroy-method="destroy">
		<constructor-arg index="0" value="elle" />
		<constructor-arg index="1" value="Study Hard!" />
	</bean>
</beans>


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

<!-- Learn 04  使用实例工厂方式实例化Bean -->
	<import resource="com/mahaochen/spring/learn05/beanLearn05.xml"/>


4、编写测试类TestSpring05.java。

public class TestSpring05 {

	public static void main(String[] args) {
		
		ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");
		Speaker speaker05 = (Speaker) appContext.getBean("speaker05");
		speaker05.teach();
		((ClassPathXmlApplicationContext) appContext).close();
	}
}


【转载使用,请注明出处:http://blog.csdn.net/mahoking

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

原文:http://blog.csdn.net/mahoking/article/details/42177159

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!