Bean的生命周期

来源:互联网 发布:mac玩fifaonline3发烫 编辑:程序博客网 时间:2024/05/22 06:52

一般来说,prototype作用域的Bean,Spring仅仅负责创建,当创建了Bean实例之后,该实例将完全交给客户端代码去管理,Spring容器不再跟踪其生命周期。而对于singleton作用域的Bean,每次客户端代码请求时都会共享同一个Bean实例,因此singleton作用域的Bean的生命周期由Spring容器负责。

对于singleton作用的Bean,Spring容器知道它何时实例化结束,何时销毁,因此Spring可以管理实例化结束之后和销毁之前的行为。分别为:
1>注入依赖关系之后
2>即将销毁Bean之前

Spring提供两种方式来管理Bean依赖关系注入之后的行为:

    1>使用init-method属性指定Bean初始化完成之后自动调用该Bean实例的哪个方法    2>实现InitializingBean接口。实现该接口需要实现一个抽象方法:void afterPropertiesSet() throws Exception ;
public class Person implements InitializingBean{    private String username ;    private String password ;    private int age ;    private String description ;    //omit setter and getter methods    @Override    public void afterPropertiesSet() throws Exception    {        System.out.println("Person Bean初始化完成") ;    }    public void initOK()    {        System.out.println("使用init-method属性指定初始化完成之后的动作") ;    }}//在配置文件中配置该Bean<bean id="persion" class="Person" init-method="initOK">    <property name=“username” value="chengxi" />    <property name="password" value="1123" />    <property name="age" value="20" />    <property name="description" value="这是一个简单的实例" /></bean>//在main程序中测试public class Test{    public static void main(String[] args)    {        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ;        Person person = context.getBean("person") ;    }}//在控制台将会输出:Person Bean初始化完成                使用init-method指定初始化完成之后的动作

同样,Spring也提供两钟方式来定制销毁Bean对象之前的行为:

    1>使用destroy-method属性指定销毁对象之前的行为方法    2>实现DisposableBean接口并实现其抽象方法:void destroy(0 throws Exception;来指定销毁对象之前的行为
public class Person implements DisposableBean{    //继上面的Person之后新增两个方法    @Override    public void destroy() throws Exception    {        System.out.println("接下来将要销毁Person Bean实例") ;    }    public void destroymethod()    {        System.out.println("指定destroy-method属性来指定销毁对象之前的行为") ;    }}//配置bean的destroy-method属性值为destroymethod ;//调用main程序测试public class test{    public static void main(String[] args)    {        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ;        Person person = context.getBean("person",Person.class) ;        //为Spring容器注册关闭钩子来检验销毁之前的行为是否执行        context.registShutdiwnHook() ;    }}

ApplicationContext.registShutdownHook()方法为Spring容器注册了一个关闭钩子,程序将会在退出JVM之前先关闭Spring容器,这样就可以保证关闭Spring容器之前调用singleton Bean实例的析构回调函数

0 0