一个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">