Spring3之 bean 定制bean特性
Customizing?the?nature?of?a?bean定制bean特性
Spring提供了几个标志接口(marker?interface),这些接口用来改变容器中bean的行为;它们包括InitializingBean和DisposableBean。实现这两个接口的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 //InitializingBeanpublic void afterPropertiesSet() throws Exception {System.out.println("in "+ ImplCustom.class+" afterPropertiesSet() method");}@Override //DisposableBeanpublic void destroy() throws Exception {System.out.println("in "+ ImplCustom.class+" destroy() method");}}
?xml中加入 bean的定义
<bean id="implCustom" style="margin-top: 0pt; margin-bottom: 0pt;">?测试:@Testpublic 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" init-method="init" destroy-method="destroy"></bean>?测试:
@Testpublic 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"
?