Spring3之 bean 定制bean特性

Customizing the nature of a bean定制bean特性

Spring提供了几个标志接口(marker interface),这些接口用来改变容器中bean的行为;它们包括InitializingBeanDisposableBean。实现这两个接口的bean在初始化和析构时容器会调用前者的afterPropertiesSet()方法,以及后者的destroy()方法。

com.spring305.test.customBean.po.ImplCustom.java

 

 

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ImplCustom implements InitializingBean,DisposableBean {

	public ImplCustom(){
		System.out.println("this is "+ImplCustom.class+"`s constractor method");
	}
	
	@Override   //InitializingBean
	public void afterPropertiesSet() throws Exception {
		System.out.println("in "+ ImplCustom.class+" afterPropertiesSet() method");
	}

	@Override  //DisposableBean
	public void destroy() throws Exception {
		System.out.println("in "+ ImplCustom.class+" destroy() method");
	}
}

 xml中加入 bean的定义

<bean id="implCustom" class="com.spring305.test.customBean.po.ImplCustom"></bean>

 测试:

@Test
public void test(){
	ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"testCustombean.xml"});
	ImplCustom impl = ctx.getBean("implCustom",ImplCustom.class);
		
}

 同时也可以在xml中用init-method,destroy-method来指定初始化回调与析构回调,这样就不用实现接口了

com.spring305.test.customBean.po.CustomBean.java

public class CustomBean {

	public CustomBean(){
		System.out.println("this is "+CustomBean.class+"`s constractor method");
	}
	
	public void init() {
		System.out.println("in "+ CustomBean.class+" init() method");
	}

	public void destroy()  {
		System.out.println("in "+ CustomBean.class+" destroy() method");
	}
}

 xml中加入

<bean id="customBean" class="com.spring305.test.customBean.po.CustomBean" init-method="init" destroy-method="destroy"></bean>

 测试:

@Test
public void testNoImpliment(){
	AbstractApplicationContext  ctx = new ClassPathXmlApplicationContext(new String[]{"testCustombean.xml"});
	CustomBean impl = ctx.getBean("customBean",CustomBean.class);
	ctx.registerShutdownHook();
}

 最后一句ctx.registerShutdownHook();是2.5文档中定义的一个关闭spring IOC容器的方法.

如上还可以在beans标签下为该标签下所有bean标签来定义初始化回调方法:default-init-method="init"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值