Spring 专题
专题目录
您的位置:java > Spring专题 > Spring Bean InitializingBean和DisposableBean实例
Spring Bean InitializingBean和DisposableBean实例
作者:--    发布时间:2019-11-20
在spring中,initializingbean和disposablebean是两个标记接口,为spring执行时bean的初始化和销毁某些行为时的有用方法。
  1. 对于bean实现 initializingbean,它将运行 afterpropertiesset()在所有的 bean 属性被设置之后。
  2. 对于 bean 实现了disposablebean,它将运行 destroy()在 spring 容器释放该 bean 之后。

示例

下面是一个例子,向您展示如何使用 initializingbean 和 disposablebean。一个 customerservice bean来实现 initializingbean和disposablebean 接口,并有一个消息(message)属性。
package com.h3.customer.services;

import org.springframework.beans.factory.disposablebean;
import org.springframework.beans.factory.initializingbean;

public class customerservice implements initializingbean, disposablebean
{
	string message;
	
	public string getmessage() {
	  return message;
	}

	public void setmessage(string message) {
	  this.message = message;
	}
	
	public void afterpropertiesset() throws exception {
	  system.out.println("init method after properties are set : " + message);
	}
	
	public void destroy() throws exception {
	  system.out.println("spring container is destroy! customer clean up");
	}
	
}

file : applicationcontext.xml

<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-2.5.xsd">

       <bean id="customerservice" class="com.h3.customer.services.customerservice">
		<property name="message" value="i'm property message" />
       </bean>
		
</beans>

执行它

package com.h3.common;

import org.springframework.context.configurableapplicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

import com.h3.customer.services.customerservice;

public class app 
{
    public static void main( string[] args )
    {
    	configurableapplicationcontext context = 
			new classpathxmlapplicationcontext(new string[] {"applicationcontext.xml"});
	
    	customerservice cust = (customerservice)context.getbean("customerservice");
    	
    	system.out.println(cust);
    	
    	context.close();
    }
}
该configurableapplicationcontext.close()将关闭该应用程序的上下文,释放所有资源,并销毁所有缓存的单例bean。它是只用于 destroy() 方的演示目的。

输出结果

init method after properties are set : i'm property message 
com.h3.customer.services.customerservice@4090c06f 
spring container is destroy! customer clean up

afterpropertiesset()方法被调用在 message 属性设置后,而 destroy()方法是在调用 context.close()之后;

建议:
不建议使用initializingbean和disposablebean的接口,因为它将你的代码紧耦合到 spring 代码中。 一个更好的做法应该是在bean的配置文件属性指定 init-method和destroy-method


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册