面试官:讲一下Spring Bean的生命周期?

article/2025/8/24 3:33:21

1. 引言

“请你描述下 Spring Bean 的生命周期?”,这是面试官考察 Spring 的常用问题,可见是 Spring 中很重要的知识点。

在这里插入图片描述

其实要记忆该过程,还是需要我们先去理解,本文将从以下两方面去帮助理解 Bean 的生命周期:

  • 生命周期的概要流程:对 Bean 的生命周期进行概括,并且结合代码来理解;

  • 扩展点的作用:详细介绍 Bean 生命周期中所涉及到的扩展点的作用。

2. 生命周期的概要流程

Bean 的生命周期概括起来就是 4 个阶段:

实例化(Instantiation)

属性赋值(Populate)

初始化(Initialization)

销毁(Destruction)

在这里插入图片描述

  1. 实例化:第 1 步,实例化一个 bean 对象;

  2. 属性赋值:第 2 步,为 bean 设置相关属性和依赖;

  3. 初始化:第 3~7 步,步骤较多,其中第 5、6 步为初始化操作,第 3、4 步为在初始化前执行,第 7 步在初始化后执行,该阶段结束,才能被用户使用;

  4. 销毁:第 8~10步,第8步不是真正意义上的销毁(还没使用呢),而是先在使用前注册了销毁的相关调用接口,为了后面第9、10步真正销毁 bean 时再执行相应的方法。

下面我们结合代码来直观的看下,在 doCreateBean() 方法中能看到依次执行了这 4 个阶段:

// AbstractAutowireCapableBeanFactory.java
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// 1. 实例化BeanWrapper instanceWrapper = null;if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}Object exposedObject = bean;try {// 2. 属性赋值populateBean(beanName, mbd, instanceWrapper);// 3. 初始化exposedObject = initializeBean(beanName, exposedObject, mbd);}// 4. 销毁-注册回调接口try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}return exposedObject;
}

由于初始化包含了第 3~7步,较复杂,所以我们进到 initializeBean() 方法里具体看下其过程(注释的序号对应图中序号):

// AbstractAutowireCapableBeanFactory.java
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {// 3. 检查 Aware 相关接口并设置相关依赖if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);return null;}, getAccessControlContext());}else {invokeAwareMethods(beanName, bean);}// 4. BeanPostProcessor 前置处理Object wrappedBean = bean;if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}// 5. 若实现 InitializingBean 接口,调用 afterPropertiesSet() 方法// 6. 若配置自定义的 init-method方法,则执行try {invokeInitMethods(beanName, wrappedBean, mbd);}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}// 7. BeanPostProceesor 后置处理if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;
}

在 invokInitMethods() 方法中会检查 InitializingBean 接口和 init-method 方法,销毁的过程也与其类似:

// DisposableBeanAdapter.java
public void destroy() {// 9. 若实现 DisposableBean 接口,则执行 destory()方法if (this.invokeDisposableBean) {try {if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {((DisposableBean) this.bean).destroy();return null;}, this.acc);}else {((DisposableBean) this.bean).destroy();}}}// 10. 若配置自定义的 detory-method 方法,则执行if (this.destroyMethod != null) {invokeCustomDestroyMethod(this.destroyMethod);}else if (this.destroyMethodName != null) {Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);if (methodToInvoke != null) {invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));}}
}

从 Spring 的源码我们可以直观的看到其执行过程,而我们记忆其过程便可以从这 4 个阶段出发,实例化、属性赋值、初始化、销毁。其中细节较多的便是初始化,涉及了 Aware、BeanPostProcessor、InitializingBean、init-method 的概念。这些都是 Spring 提供的扩展点,其具体作用将在下一节讲述。

3. 扩展点的作用

3.1 Aware 接口

若 Spring 检测到 bean 实现了 Aware 接口,则会为其注入相应的依赖。所以通过让 bean 实现 Aware 接口,则能在 bean 中获得相应的 Spring 容器资源

Spring 中提供的 Aware 接口有:

  1. BeanNameAware:注入当前 bean 对应 beanName;

  2. BeanClassLoaderAware:注入加载当前 bean 的 ClassLoader;

  3. BeanFactoryAware:注入 当前BeanFactory容器 的引用。

其代码实现如下:

// AbstractAutowireCapableBeanFactory.java
private void invokeAwareMethods(final String beanName, final Object bean) {if (bean instanceof Aware) {if (bean instanceof BeanNameAware) {((BeanNameAware) bean).setBeanName(beanName);}if (bean instanceof BeanClassLoaderAware) {((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);}if (bean instanceof BeanFactoryAware) {((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);}}
}

以上是针对 BeanFactory 类型的容器,而对于 ApplicationContext 类型的容器,也提供了 Aware 接口,只不过这些 Aware 接口的注入实现,是通过 BeanPostProcessor 的方式注入的,但其作用仍是注入依赖。

  1. EnvironmentAware:注入 Enviroment,一般用于获取配置属性;

  2. EmbeddedValueResolverAware:注入 EmbeddedValueResolver(Spring EL解析器),一般用于参数解析;

  3. ApplicationContextAware(ResourceLoader、ApplicationEventPublisherAware、MessageSourceAware):注入 ApplicationContext 容器本身。

其代码实现如下:

// ApplicationContextAwareProcessor.java
private void invokeAwareInterfaces(Object bean) {if (bean instanceof EnvironmentAware) {((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());}if (bean instanceof EmbeddedValueResolverAware) {((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);}if (bean instanceof ResourceLoaderAware) {((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);}if (bean instanceof ApplicationEventPublisherAware) {((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);}if (bean instanceof MessageSourceAware) {((MessageSourceAware)bean).setMessageSource(this.applicationContext);}if (bean instanceof ApplicationContextAware) {((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);}}

3.2 BeanPostProcessor

BeanPostProcessor 是 Spring 为修改 bean提供的强大扩展点,其可作用于容器中所有 bean,其定义如下:

public interface BeanPostProcessor {// 初始化前置处理default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {return bean;}// 初始化后置处理default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {return bean;}}

常用场景有:

  1. 对于标记接口的实现类,进行自定义处理。例如3.1节中所说的ApplicationContextAwareProcessor,为其注入相应依赖;再举个例子,自定义对实现解密接口的类,将对其属性进行解密处理;

  2. 为当前对象提供代理实现。例如 Spring AOP 功能,生成对象的代理类,然后返回。

// AbstractAutoProxyCreator.java
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {TargetSource targetSource = getCustomTargetSource(beanClass, beanName);if (targetSource != null) {if (StringUtils.hasLength(beanName)) {this.targetSourcedBeans.add(beanName);}Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);this.proxyTypes.put(cacheKey, proxy.getClass());// 返回代理类return proxy;}return null;
}

3.3 InitializingBean 和 init-method

InitializingBean 和 init-method 是 Spring 为 bean 初始化提供的扩展点。

InitializingBean接口的定义如下:

public interface InitializingBean {void afterPropertiesSet() throws Exception;
}

在 afterPropertiesSet() 方法写初始化逻辑。

指定 init-method 方法,指定初始化方法:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="demo" class="com.chaycao.Demo" init-method="init()"/></beans>

DisposableBean 和 destory-method 与上述类似,就不描述了。

4. 总结

最后总结下如何记忆 Spring Bean 的生命周期:

  • 首先是实例化、属性赋值、初始化、销毁这 4 个大阶段;

  • 再是初始化的具体操作,有 Aware 接口的依赖注入、BeanPostProcessor 在初始化前后的处理以及 InitializingBean 和 init-method 的初始化操作;

  • 销毁的具体操作,有注册相关销毁回调接口,最后通过DisposableBean 和 destory-method 进行销毁。

5. 参考

https://juejin.im/post/5e4791a7f265da5715630629


http://chatgpt.dhexx.cn/article/qJoNuIWW.shtml

相关文章

Spring Bean的生命周期(非常详细)

生命周期图 文章目录 前言一、生命周期流程图&#xff1a;二、各种接口方法分类三、演示 前言 Spring作为当前Java最流行、最强大的轻量级框架&#xff0c;受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容…

Spring 中Bean的生命周期

目录 Bean的生命周期 五个阶段 下面是一个bean对象创建到销毁经历过的方法。 图示​ 问答 普通Java类是在哪一步变成beanDefinition的 推荐视频&#xff1a; 阿里专家耗时一年&#xff0c;终于把Spring源码AOP、IOC、Ben生命周期、事物、设计模式以及循环依赖讲全了_哔哩…

Spring之Bean的生命周期详解

通过前面多个接口的介绍了解了Bean对象生命周期相关的方法&#xff0c;本文就将这些接口的方法串起来&#xff0c;来了解Bean的完整的生命周期。而介绍Bean的生命周期也是面试过程中经常会碰到的一个问题&#xff0c;如果不注意就跳坑里啦~~ Spring之Bean对象的初始化和销毁方法…

Bean的生命周期及演示

文章目录 一、介绍概念Bean生命周期组成&#xff1a; 二、实例演示 一、介绍 概念 Bean的生命周期是指一个Bean对象从创建到销毁的整个存在过程。 Bean生命周期组成&#xff1a; 1.实例化Bean&#xff08;为Bean分配内存空间&#xff09; 2.属性注入 (Bean注入和装配) 3.Bean…

面试题:Spring Bean的生命周期

最近在复习Spring的面试题&#xff0c;关于Spring Bean的生命周期一直没有很深入的理解&#xff0c;自己结合源码参考了网上的几篇文章&#xff0c;写了一点东西&#xff0c;方便理解。 Spring 启动&#xff0c;查找并加载需要被 Spring 管理的 Bean&#xff0c;进行 Bean 的…

Bean的生命周期和作用域

Bean的生命周期 Bean的执行流程&#xff1a; Bean 执行流程&#xff1a;启动Spring 容器 -> 实例化 Bean&#xff08;分配内存空间&#xff0c;从无到有&#xff09;-> Bean 注册到 Spring 中&#xff08;存操作&#xff09; -> 将 Bean 装配到需要的类中&#xff08;…

关于Spring Bean的生命周期

一、简介 Spring Bean 的生命周期在整个 Spring 中占有很重要的位置&#xff0c;从BeanFactory或ApplicationContext取得的实例为Singleton&#xff0c;也就是预设为每一个Bean的别名只能维持一个实例&#xff0c;而不是每次都产生一个新的对象使用Singleton模式产生单一实…

7、Bean的生命周期

Spring其实就是一个管理Bean对象的工厂。它负责对象的创建&#xff0c;对象的销毁等。 所谓的生命周期就是&#xff1a;对象从创建开始到最终销毁的整个过程。 什么时候创建Bean对象&#xff1f; 创建Bean对象的前后会调用什么方法&#xff1f; Bean对象什么时候销毁&#…

【一篇搞懂】 bean的生命周期详解

概述 Spring中的一个Bean从生到灭要经历很多过程,总体分为Bean定义、实例化、属性赋值(依赖注入)、初始化、生存期、销毁几个阶段: ​​​​​​​​ 下面是一个细化的Bean生命周期图: 过程比较复杂,重点关注Bean的定义、初始化、销毁过程,可以抓住重点: BeanPostPro…

Bean 生命周期详解

Spring Bean 的生命周期&#xff0c;面试时非常容易问&#xff0c;这不&#xff0c;前段时间就有个粉丝去字节面试&#xff0c;因为不会回答这个问题&#xff0c;一面都没有过。 如果只讲基础知识&#xff0c;感觉和网上大多数文章没有区别&#xff0c;但是我又想写得稍微深入…

【Spring】Spring的Bean的生命周期

作者简介&#xff1a;大家好&#xff0c;我是五度鱼&#xff0c;一个普通的Java领域博主&#xff0c;不停输出Java技术博客和干货。座右铭&#xff1a;锲而不舍&#xff0c;金石可镂。个人主页&#xff1a;五度鱼学Java的主页 文章目录 前言1. 什么是Bean的生命周期&#xff1f…

Spring中bean的生命周期(最详细)

Spring Bean的生命周期是Spring面试热点问题。Spring Bean的生命周期指的是从一个普通的Java类变成Bean的过程&#xff0c;深知Spring源码的人都知道这个给面试官讲的话大可讲30分钟以上&#xff0c;如果你不没有学习过Spring的源码&#xff0c;可能就知道Aware接口和调用init方…

Bean的生命周期

目录 一&#xff0c;bean的初始化 &#xff08;1&#xff09;Spring的IOC和AOP&#xff1a; &#xff08;2&#xff09;Spring Bean的生命周期&#xff1a; 二&#xff0c;单例模式与多例模式的区别 区别 《代码演示》 前言 回顾&#xff1a;Servlet的生命 初始化&#x…

bean的生命周期(最全最细讲解)

一、bean生命周期&#xff1a; 其定义为&#xff1a;从对象的创建到销毁的过程。而Spring中的一个Bean从开始到结束经历很多过程&#xff0c;但总体可以分为六个阶段Bean定义、实例化、属性赋值、初始化、生存期、销毁。 二、案例代码演示 1.首先我们来创建一个包&#xff0…

去字节面试,直接让人出门左拐:Bean 生命周期都不知道!

Spring Bean 的生命周期&#xff0c;面试时非常容易问&#xff0c;这不&#xff0c;前段时间就有个粉丝去字节面试&#xff0c;因为不会回答这个问题&#xff0c;一面都没有过。 如果只讲基础知识&#xff0c;感觉和网上大多数文章没有区别&#xff0c;但是我又想写得稍微深入…

Spring Bean生命周期,好像人的一生。。

大家好&#xff0c;我是老三&#xff0c;上节我们手撸了一个简单的IOC容器五分钟&#xff0c;手撸一个Spring容器&#xff01;&#xff0c;这节我们来看一看Spring中Bean的生命周期&#xff0c;我发现&#xff0c;和人的一生真的很像。 简单说说IoC和Bean IoC&#xff0c;控制…

Spring中bean的生命周期

Spring中的bean的生命周期主要包含四个阶段&#xff1a;实例化Bean --&#xff1e; Bean属性填充 --&#xff1e; 初始化Bean --&#xff1e;销毁Bean 首先是实例化Bean&#xff0c;当客户向容器请求一个尚未初始化的bean时&#xff0c;或初始化bean的时候需要注入另一个尚末初…

一文读懂 Spring Bean 的生命周期

欢迎大家关注我的微信公众号【老周聊架构】&#xff0c;Java后端主流技术栈的原理、源码分析、架构以及各种互联网高并发、高性能、高可用的解决方案。 一、前言 今天我们来说一说 Spring Bean 的生命周期&#xff0c;小伙伴们应该在面试中经常遇到&#xff0c;这是正常现象。…

ubuntu 换源深层次解析

换源也是一个容易出错的问题&#xff0c;本文以树莓派为例展开&#xff0c;x86也是一样的操作。 那么假设成立的话&#xff0c;就要记住我们是在树莓派&#xff08;arm&#xff09;上安装的ubuntu&#xff0c;不是X86&#xff0c;不是amd。 安装好系统后&#xff0c;我们第一…

[Linux]Ubuntu 换源 20.04 阿里源

注意&#xff0c;这篇文章其实不是简单的教你怎么换源&#xff0c;而是示例一种方法来换20.04的阿里源&#xff0c;其他源和版本大同小异。 笔者在写这篇文章的时候&#xff0c;20.04 还没有release出来正式版&#xff0c;但是已经可以在仓库里看到有源存在了&#xff0c;故写下…