本文共 1854 字,大约阅读时间需要 6 分钟。
有时需要在 Bean 属性值 set 好之后和 Bean 销毁之前做一些事情,比如检查 Bean 中某个属性是否被正常的设置好值。Spring 框架提供了多种方法,让我们可以在 Spring Bean 的生命周期中执行 initialization 和 pre-destroy 方法。
1. 实现 InitializingBean 和 DisposableBean 接口
这两个接口都只包含一个方法。通过实现 InitializingBean 接口的 afterPropertiesSet()
方法可以在 Bean 属性值设置好之后做一些操作,实现 DisposableBean 接口的 destroy() 方法可以在销毁Bean之前做一些操作。
例子如下:
public class TestService implements InitializingBean,DisposableBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("执行 InitializingBean 接口的 afterPropertiesSet 方法"); } @Override public void destroy() throws Exception { System.out.println("执行 DisposableBean 接口的 destroy 方法"); }}
这种方法比较简单,但是不建议使用,因为这样会将 Bean 的实现和 Spring 框架耦合在一起。
2. 在 bean 的配置文件中指定 init-method 和 destroy-method 方法
Spring 允许我们创建自己的 init 方法和 destroy 方法,只要在 Bean 的配置文件中指定 init-method 和 destroy-method 的值就可以在 Bean 初始化时和销毁之前执行一些操作。
例子如下:
public class TestService { //通过 destroy-method 属性指定的销毁方法 public void destroyMethod() throws Exception { System.out.println("执行配置的 destroy-method"); } // 通过 init-method 属性指定的初始化方法 public void initMethod() throws Exception { System.out.println("执行配置的 init-method"); }}
配置文件中的配置:
需要注意的是吗,自定义的 init-method 和 post-method 方法可以抛异常,但是不能有参数。
这种方式比较推荐,因为可以自己创建方法,无需将 Bean 的实现直接依赖于 spring 的框架。
3.使用 @PostConstruct
和 @PreDestroy
注解
除了 xml 配置的方式,Spring 也支持用 @PostConstruct
和 @PreDestroy
注解来指定 init
和 destroy
方法。这两个注解均在 javax.annotation
包中。为了注解可以生效,需要在配置文件中定义 org.springframework.context.annotation.CommonAnnotationBeanPostProcessor 或 context:annotation-config
例子如下:
public class GiraffeService { @PostConstruct public void initPostConstruct(){ System.out.println("执行PostConstruct注解标注的方法"); } @PreDestroy public void preDestroy(){ System.out.println("执行preDestroy注解标注的方法"); }}
配置文件:
转载地址:http://ensin.baihongyu.com/