ApplicationContextAware, SmartInitializingSingleton, DisposableBean 这三个接口的作用和运行时机

让我们逐个解释这三个接口:ApplicationContextAwareSmartInitializingSingletonDisposableBean,以及它们中的方法何时运行。

1. ApplicationContextAware

ApplicationContextAware 接口是 Spring Framework 提供的一个接口,用于让实现类获取 Spring 应用程序上下文(ApplicationContext)。当一个类实现了 ApplicationContextAware 接口后,Spring 容器会在将应用程序上下文(ApplicationContext)注入到实现类时调用 setApplicationContext() 方法。

方法:
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
作用:
  • 通过实现 ApplicationContextAware 接口,类可以获取到 Spring 容器的上下文,从而可以在需要时访问容器中的其他 bean、获取配置信息等。
运行时机:
  • setApplicationContext() 方法会在 Spring 容器将应用程序上下文注入到实现类时调用。通常发生在 Spring 容器启动过程中。

2. SmartInitializingSingleton

SmartInitializingSingleton 接口是 Spring Framework 提供的一个特殊接口,用于在所有单例 bean 都初始化完成后执行一些自定义逻辑。当一个类实现了 SmartInitializingSingleton 接口后,Spring 容器会在所有单例 bean 初始化完成后调用 afterSingletonsInstantiated() 方法。

方法:
void afterSingletonsInstantiated();
作用:
  • 通过实现 SmartInitializingSingleton 接口,类可以在 Spring 容器启动完成后执行特定的初始化逻辑,确保所有单例 bean 都已经初始化完成。
运行时机:
  • afterSingletonsInstantiated() 方法会在 Spring 容器启动完成后调用,即所有单例 bean 都初始化完成后执行。

3. DisposableBean

DisposableBean 接口是 Spring Framework 提供的一个接口,用于在销毁 bean 时执行一些清理工作。当一个类实现了 DisposableBean 接口后,Spring 容器在销毁该 bean 时会调用 destroy() 方法。

方法:
void destroy() throws Exception;
作用:
  • 通过实现 DisposableBean 接口,类可以在 bean 被销毁时执行一些清理操作,如释放资源、关闭连接等。
运行时机:
  • destroy() 方法会在 Spring 容器销毁该 bean 时调用,通常发生在 Spring 容器关闭或销毁时。

运行时机总结:

  • ApplicationContextAware 接口的 setApplicationContext() 方法会在 Spring 容器将应用程序上下文注入到实现类时调用。
  • SmartInitializingSingleton 接口的 afterSingletonsInstantiated() 方法会在所有单例 bean 初始化完成后调用,即 Spring 容器启动完成后执行。
  • DisposableBean 接口的 destroy() 方法会在 Spring 容器销毁该 bean 时调用,通常发生在 Spring 容器关闭或销毁时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值