在Spring中,可以使用 init-method 和 destroy-method 在bean 配置文件属性用于在bean初始化和销毁某些动作时。这是用来替代 InitializingBean和DisposableBean接口。
示例
这里有一个例子向您展示如何使用 init-method 和 destroy-method。
File:CustomerService.java
public class CustomerService{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void cleanUp() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
}
public void initIt() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
@Override
public String toString() {
return "CustomerService [message=" + message + "]";
}
}
File : beans.xml, 在bean中定义了init-method和destroy-method属性。
<?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">
<bean id="customerService" class="com.ray.common.services.CustomerService"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="I'm property message"/>
</bean>
</beans>
执行程序:
public class Test {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
CustomerService cust = (CustomerService) ctx.getBean("customerService");
System.out.println(cust);
ctx.close();
}
}
ConfigurableApplicationContext.close将关闭应用程序上下文,释放所有资源,并销毁所有缓存的单例bean。
输出
二月 22, 2018 10:33:24 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3fa77460: startup date [Thu Feb 22 22:33:24 CST 2018]; root of context hierarchy
二月 22, 2018 10:33:24 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
Init method after properties are set : I'm property message
CustomerService [message=I'm property message]
二月 22, 2018 10:33:25 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3fa77460: startup date [Thu Feb 22 22:33:24 CST 2018]; root of context hierarchy
Spring Container is destroy! Customer clean up
initIt()方法被调用,消息属性设置后,在 context.close()调用后,执行 cleanUp()方法;
建议使用init-method 和 destroy-methodbean 在Bena配置文件,而不是执行 InitializingBean 和 DisposableBean 接口,也会造成不必要的耦合代码在Spring。