Spring容器的生命周期

节选Spring的DOC


Bean factory implementations should support the standard bean lifecycle interfaces as far as possible. The full set of initialization methods and their standard order is:
1. BeanNameAware's setBeanName
2. BeanClassLoaderAware's setBeanClassLoader
3. BeanFactoryAware's setBeanFactory
4. ResourceLoaderAware's setResourceLoader (only applicable when running in an application context)
5. ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context)
6. MessageSourceAware's setMessageSource (only applicable when running in an application context)
7. ApplicationContextAware's setApplicationContext (only applicable when running in an application context)
8. ServletContextAware's setServletContext (only applicable when running in a web application context)

9. postProcessBeforeInitialization methods of BeanPostProcessors
10. InitializingBean's afterPropertiesSet
11. a custom init-method definition
12. postProcessAfterInitialization methods of BeanPostProcessors 

On shutdown of a bean factory, the following lifecycle methods apply:
1. DisposableBean's destroy
2. a custom destroy-method definition


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring 容器生命周期可以分为三个阶段:实例化、初始化和销毁。 1. 实例化阶段:在这个阶段,Spring 容器会根据配置文件或注解等方式,创建并实例化所有的 Bean 对象。这个阶段主要包括以下步骤: - 加载配置文件或扫描注解,获取所有的 Bean 定义。 - 根据 Bean 定义创建相应的 Bean 实例。 - 对于单例的 Bean,容器会在这个阶段创建并保留其实例。 2. 初始化阶段:在实例化阶段完成后,Spring 容器会对实例化的 Bean 进行初始化。这个阶段主要包括以下步骤: - 设置 Bean 的属性值,包括依赖注入。 - 调用 Bean 的初始化方法,可以通过配置文件或注解指定初始化方法。 - 执行 BeanPostProcessor 的前置处理方法。 - 对于单例的 Bean,容器会在这个阶段完成其初始化。 3. 销毁阶段:在容器关闭时,会执行销毁阶段,对已经初始化的 Bean 进行销毁和清理工作。这个阶段主要包括以下步骤: - 调用 Bean 的销毁方法,可以通过配置文件或注解指定销毁方法。 - 执行 BeanPostProcessor 的后置处理方法。 需要注意的是,对于单例的 Bean,默认情况下 Spring 容器会管理其完整的生命周期,而对于原型(prototype)作用域的 Bean,则不负责销毁。如果需要在原型 Bean 销毁时执行一些清理工作,可以使用自定义的销毁回调方法或者手动管理。 以上是 Spring 容器的基本生命周期,可以通过配置文件或注解等方式来控制和管理 Bean 的生命周期

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值