1. 程式人生 > >Spring《二》 Bean的生命周期

Spring《二》 Bean的生命周期

pro msg public sys ini text cto onf con

Bean初始化

1、bean中實現public void init();方法,config.xml中增加init-method="init" 屬性。

2、bean實現接口InitializingBean,實現方法afterPropertiesSet,配置文件無需改動。

Bean的使用

1、

HelloWorld helloWorld=new HelloWorld();

BeanWrapper bw=new BeanWrapperImpl(helloWorld);

bw.setPropertyValue("msg","HelloWorld");

2、

InputStream is=new FileInputStream("config.xml");

XmlBeanFactory factory=new XmlBeanFactory(is);

HelloWorld helloWorld=(HelloWorld)factory.getBean("HelloWorld");

3、

ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");

HelloWorld hw=(HelloWorld)actx.getBean("HelloWorld");

Bean的銷毀

1、bean中實現方法public void cleanup();,bean配置中增加destroy-method="cleanup" 屬性

2、bean類實現DisposableBean,並復寫public void destroy();配置文檔無需變動。

Spring《二》 Bean的生命周期