欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring3之 bean 定制bean特性

程序员文章站 2022-05-23 10:20:28
...

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"