Spring Bean的完整生命周期回调

本文详细阐述了Spring中Bean的生命周期回调,包括init和destroy方法的不同形式,如接口、注解以及XML配置,并讨论了它们的执行顺序。推荐使用@PostConstruct和@PreDestroy注解,避免与Spring高耦合。示例展示了Bean从创建到销毁的过程,包括属性注入、初始化和销毁的方法调用顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bean的生命周期回调

​ Bean的生命周期回调主要是在Bean对象创建和销毁的过程中会执行一些init和destroy方法,了解不同形式的init和destroy声明方法,以及它们之间的先后执行顺序会有助于我们理解Bean的生命周期过程。下文主要介绍了生命周期回调的各种使用方式,以及在Spring中是如何实现的。

常用的三种形式:

  • InitializingBeanDisposableBean接口,分别实现afterPropertiesSetdestroy方法;
  • JSR-250下的@PostConstruct@PreDestroy注解;
  • 在Spring xml文件中声明init-methoddestroy-method 属性。

不推荐使用InitializingBean、DisposableBean接口,因为可能会导致和Spring高耦和。

多种形式共同作用于一个Bean时,按照如下顺序执行:

  • @PostConstruct注解指定的方法;
  • InitializingBean接口实现的afterPropertiesSet()方法;
  • init-method属性指定的方法;
  • @PreDestroy注解指定的方法;
  • DisposableBean接口实现的destroy方法;
  • destroy-method属性指定的方法。

示例:

public class X implements InitializingBean, DisposableBean {
   

    @PostConstruct
    public void postConstruct() {
   
        System.out.println("PostConstruct.....");
    }

    public X() {
   
        System.out.println("X construct...");
    }

    @PreDestroy
    public void preDestroy() {
   
        System.out.println("PreDestroy.....");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
   
        System.out.println("afterPropertiesSet...");
    }

    @Override
    public void destroy() throws Exception {
   
        System.out.println("destroy...");
    }

    public void init() {
   
        System.out.println("init...");
    }

    public void destroyMethod() {
   
        System.out.println("destroyMethod..."
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值