Spring bean 初始化和销毁

initialization 和 destroy

有时需要在 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");
    }
}

配置文件中的配置:

<bean name="giraffeService" class="cn.mariojd.spring.service.TestService" init-method="initMethod" destroy-method="destroyMethod">
</bean>

需要注意的是吗,自定义的 init-method 和 post-method 方法可以抛异常,但是不能有参数。

这种方式比较推荐,因为可以自己创建方法,无需将 Bean 的实现直接依赖于 spring 的框架。

3.使用 @PostConstruct@PreDestroy 注解

除了 xml 配置的方式,Spring 也支持用 @PostConstruct@PreDestroy 注解来指定 initdestroy 方法。这两个注解均在 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注解标注的方法");
    }
}

配置文件:

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值