spring 允许 Bean 在初始化完成后以及销毁前执行特定的操作

来源:互联网 发布:centos解压命令 编辑:程序博客网 时间:2024/05/21 22:43

Spring 容器中的 Bean 是有生命周期的,spring 允许 Bean 在初始化完成后以及销毁前执行特定的操作。下面是常用的三种指定特定操作的方法:

  1. 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
  2. 通过<bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
  3. 在指定方法上加上@PostConstruct或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。

这几种配置方式,执行顺序是怎样的呢?我们通过例子来研究下:

package com.xiaodou._2b_dashboard_report.test1;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;import org.springframework.context.support.ClassPathXmlApplicationContext;public class InitAndDestroySeqBean implements InitializingBean,DisposableBean{  public InitAndDestroySeqBean(){    System.out.println("执行构造方法");  }  @PostConstruct  public void postConstruct(){    System.out.println("postConstruct");  }  @Override  public void afterPropertiesSet() throws Exception {    System.out.println("afterPropertiesSet");  }  public void initMethod(){    System.out.println("initMethod");  }  @PreDestroy  public void preDestroy(){    System.out.println("preDestroy");  }  @Override  public void destroy() throws Exception {    System.out.println("destroy");  }  public void destroyMethod(){    System.out.println("destroyMethod");  }  public static void main(String[] args) {    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("conf/core/xd_2b_dashboard_report.xml");      context.close();    }}

运行InitAndDestroySeqBean的main方法,结果如下:

执行构造方法postConstructafterPropertiesSetinitMethodpreDestroydestroydestroyMethod

从执行结果可以看出:
Bean在实例化的过程中:Constructor > @PostConstruct >InitializingBean > init-method

Bean在销毁的过程中:@PreDestroy > DisposableBean > destroy-method

1 0
原创粉丝点击