让我们逐个解释这三个接口:ApplicationContextAware
、SmartInitializingSingleton
和 DisposableBean
,以及它们中的方法何时运行。
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 容器关闭或销毁时。