Spring中配置Bean的初始化和销毁

一个Bean在使用new创建完成之后,再使用这个Bean之前,有时候需要初始化这个Bean所占用的资源;最后,在这个Bean在销毁之前,销毁它所占用的资源。在Spring中,可以在bean标签中配置inti-method和destroy-method来为这个Bean指定初始化方法和销毁方法。

假设有一个数据源DataSource的Bean,在使用之前,应该去读取database.properties文件来进行数据库信息配置,并且准备好一个连接池(Connection pool),就可以为这个Bean指定一个初始化方法

public class DataSource {

	private ConnectionPool pool;
	
	private Properties conigFile;
	
	/**
	 * 读取配置文件并创建连接池
	 * @throws Exception
	 */
	public void initDataSource() throws Exception
	{
		//读取配置文件
		//创建连接池
	}
	
	/**
	 * 释放所占用的资源
	 * @throws Exception
	 */
	public void releaseDataSource() throws Exception
	{
		//释放连接池
	}
}
这里省略了getter和setter方法。

applicationContext文件配置如下

	<bean id="dataSource" class="com.daniel.model.bean.DataSource" 
		  init-method="initDataSource" 
		  destroy-method="releaseDataSource"/>

若果有很多Bean都需要配置初始化方法和销毁方法,那么可以在beans标签中配置default-init-method和default-destroy-method来指定所有Bean的默认初始化方法和销毁方法,当beans和bean同时配置了初始化方法和销毁方法,以bean配置的为准(靠近准则)。

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/aop
						http://www.springframework.org/schema/beans/spring-aop-3.0.xsd" 
                                                default-init-method="init" default-destroy-method="destroy">


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值