spring中bean的生命周期

一.bean的定义

 在配置文件中进行配置bean

二.bean的初始化

  1、在配置文档中通过指定init-method 属性来完成
             在Bean的类中实现一个初始化Bean属性的方法,如init(),如:
                public class HelloWorld{
                      public String msg=null;
                      public Date date=null;
                  
                      public void init() {
                            msg="HelloWorld";
                            date=new Date();
                      }
                      ......
                }
             然后,在配置文件中设置init-mothod属性:  
             id="HelloWorld" class="com.pqf.beans.HelloWorld" init-mothod="init" >
           


       2、实现 org.springframwork.beans.factory.InitializingBean接口
             Bean实现InitializingBean接口,并且增加 afterPropertiesSet() 方法:

             public class HelloWorld implement InitializingBean {
                      public String msg=null;
                      public Date date=null;
                  
                      public void afterPropertiesSet() {
                            msg="向全世界问好!";
                            date=new Date();
                      }
                      ......
                }
         
             那么,当这个Bean的所有属性被Spring的BeanFactory设置完后,会自动调用afterPropertiesSet()方法对Bean进行初始化,于是,配置文件就不用指定 init-method属性了。

三.bean的调用

使用ApplicationConttext
       ApplicationContext actx=new FleSystemXmlApplicationContext("config.xml");
       HelloWorld hw=(HelloWorld) actx.getBean("HelloWorld");
       System.out.println(hw.getMsg());

四.bean的销毁

1、使用配置文件中的 destory-method 属性
          与初始化属性 init-methods类似,在Bean的类中实现一个撤销Bean的方法,然后在配置文件中通过 destory-method指定,那么当bean销毁时,Spring将自动调用指定的销毁方法。

       2、实现 org.springframwork.bean.factory.DisposebleBean接口
          如果实现了DisposebleBean接口,那么Spring将自动调用bean中的Destory方法进行销毁,所以,Bean中必须提供Destory方法。

 

posted @ 2012-11-06 10:32  闭眼  阅读(97)  评论(0编辑  收藏  举报