码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中bean的init-method和destroy-method

时间:2015-07-03 15:46:18      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

只有bean的生命周期为singleton且在程序末尾关闭容器时才会执行destroy-method方法

//ServiceTest.java

package com.mnmlist.initDestroy;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServiceTest {
	public static void main(String args[])
	{
		ApplicationContext ctx=new ClassPathXmlApplicationContext("InitDestroy.xml");
		Service service=(Service)ctx.getBean("service");
		service.consumeService();
		((ClassPathXmlApplicationContext)ctx).close();//关闭容器
	}
	
	
}

//Service.java

package com.mnmlist.initDestroy;

public class Service {
	public void arrangeTable()
	{
		System.out.println("I'm arranging the table!");
	}
	public void cleanTable()
	{
		System.out.println("I have clean the table!");
	}
	public void consumeService()
	{
		System.out.println("I'm consume the service!");
	}
}

//配置文件

<?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-3.0.xsd">
	<bean id="service" class="com.mnmlist.initDestroy.Service" scope="singleton"//单例模式
	destroy-method="cleanTable"
		init-method="arrangeTable"
		 />
</beans>

结果如图:

技术分享


版权声明:本文为博主原创文章,未经博主允许不得转载。

Spring中bean的init-method和destroy-method

标签:

原文地址:http://blog.csdn.net/mnmlist/article/details/46742269

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!