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

5 篇文章 0 订阅

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方法,结果如下:

执行构造方法
postConstruct
afterPropertiesSet
initMethod
preDestroy
destroy
destroyMethod

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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值