Spring《二》 Bean的生命周期

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();配置文档无需变动。

原文地址:https://www.cnblogs.com/swordyt/p/7001144.html