当前位置: 首页 > news >正文

SpringBoot原理揭秘--BeanFactory和ApplicationContext

本章我们来讲一讲BeanFactory和ApplicationContext以及其子类的作用。

BeanFactory

beanFactory是ioc容器的顶层抽象,它仅定义最基础的bean对象的管理。

beanFactory是spring FrameWork中用于访问bean容器的最基本的根接口。而后续的一些继承类则是扩展了某些额外的特性。

beanFactory主要有以下几个基础特性:

/*** This interface is implemented by objects that hold a number of bean definitions,* each uniquely identified by a String name. Depending on the bean definition,* the factory will return either an independent instance of a contained object* (the Prototype design pattern), or a single shared instance (a superior* alternative to the Singleton design pattern, in which the instance is a* singleton in the scope of the factory). Which type of instance will be returned* depends on the bean factory configuration: the API is the same. Since Spring* 2.0, further scopes are available depending on the concrete application* context (for example, "request" and "session" scopes in a web environment).**/
public interface BeanFactory 

1. 基础容器(用来存储生成的bean)

上述注释则是取自springBoot官方源码的注释,上面说到beanFactory负责管理多个beanDefinition,而这些beanDefinition则是通过beanName来确定唯一标识的。同时也讲述了scope作用域,有单例和原型两种作用域,至于返回bean属于哪种则完全是由配置来决定的

2. 定义了作用域的概念(用于控制 Bean 实例的生命周期和创建方式)

3. 集成坏境配置(可以读取系统环境变量、JVM 参数、配置文件(如application.properties)等外部配置)

4. 支持多种类型的配置源(可以从不同的配置源中读取bean信息然后将其加入到容器中)

5. 层次性的设计(即一个容器可以有父容器和子容器,形成继承关系)

  • 子容器可以访问父容器中的 Bean,但父容器不能访问子容器的 Bean。
  • 这种设计在多层架构中非常实用,例如:
    • Web 层的DispatcherServlet对应一个子容器,管理 Controller;
    • 根容器管理 Service、Repository 等,子容器可引用根容器的 Bean,但反之不行,避免了层间的耦合。

6. 完整的生命周期控制机制

BeanFactory对 Bean 的生命周期进行全流程管理,从创建到销毁的每个阶段都可干预:

  • 实例化:调用构造方法创建 Bean 对象。
  • 属性注入:为 Bean 的属性赋值(如通过setter方法或构造器注入依赖)。
  • 初始化:执行初始化方法,如@PostConstruct注解的方法、实现InitializingBean接口的afterPropertiesSet()
  • 使用:Bean 处于可用状态,供其他组件调用。
  • 销毁:容器关闭时执行销毁方法,如@PreDestroy注解的方法、实现DisposableBean接口的destroy()
  • 此外,还可通过 BeanPostProcessor 等扩展点,在初始化前后添加自定义逻辑(如 AOP 代理的生成)。

那么我们来比较一下层次性的设计和双亲委派机制

对比维度父子 BeanFactory 机制双亲委派机制
查找方向自底向上(子→父)自顶向下(父→子)
核心目标实现 Bean 的分层管理和隔离保证类加载的安全性和一致性
冲突处理子容器 Bean 覆盖父容器同名 Bean父类加载器加载的类优先
应用范围Spring IoC 容器内部Java 虚拟机类加载过程

简单来说:父子 BeanFactory 是 "子优先,父补充",为了灵活管理 Bean;双亲委派是 "父优先,子兜底",为了安全加载类。两者虽有层级关系,但设计思想和目的完全不同。

HierarchicalBeanFactory 

HierarchicalBeanFactory 是 Spring 框架中一个重要的接口,它继承自 BeanFactory,专门用于支持具有层级关系的容器结构,是实现父子 BeanFactory 与父 BeanFactory 层级联动的核心接口。

Sub-interface implemented by bean factories that can be part of a hierarchy.
The corresponding setParentBeanFactory method for bean factories that allow setting the parent in a configurable fashion can be found in the ConfigurableBeanFactory interface.
自:
07.07.2003
请参阅:
org. springframework. beans. factory. config. ConfigurableBeanFactory. setParentBeanFactory
作者:
Rod Johnson, Juergen Hoeller

上述springBoot源码描述也清晰的说明了允许一个 bean 工厂拥有父级 bean 工厂,也就是为层级结构提供有力的支持

	/*** Return the parent bean factory, or {@code null} if there is none.*/@NullableBeanFactory getParentBeanFactory();/*** Return whether the local bean factory contains a bean of the given name,* ignoring beans defined in ancestor contexts.* <p>This is an alternative to {@code containsBean}, ignoring a bean* of the given name from an ancestor bean factory.* @param name the name of the bean to query* @return whether a bean with the given name is defined in the local factory* @see BeanFactory#containsBean*/boolean containsLocalBean(String name);

同时扩展了两个方法,分别是获取父bean工厂的工厂对象以及根据bean名称判断当前bean是否存在。在第二个查询bean的时候,只会查询当前bean工厂内的bean而不会去查看是否存在父工厂的bean。同时一个bean在子工厂中存在,那么在父工厂中也可能存在。之前所说的单例仅仅是在当前工厂中是单例存在的,但再其他工厂中则不能保证不会含有这个bean

ListableBeanFactory 

ListableBeanFactory 是 Spring 框架中 BeanFactory 接口的重要扩展,核心作用是提供批量操作和查询 Bean 的能力,解决了基础 BeanFactory 只能单例获取 Bean 的限制。

/*** Extension of the {@link BeanFactory} interface to be implemented by bean factories* that can enumerate all their bean instances, rather than attempting bean lookup* by name one by one as requested by clients. BeanFactory implementations that* preload all their bean definitions (such as XML-based factories) may implement* this interface.** <p>If this is a {@link HierarchicalBeanFactory}, the return values will <i>not</i>* take any BeanFactory hierarchy into account, but will relate only to the beans* defined in the current factory. Use the {@link BeanFactoryUtils} helper class* to consider beans in ancestor factories too.** <p>The methods in this interface will just respect bean definitions of this factory.* They will ignore any singleton beans that have been registered by other means like* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s* {@code registerSingleton} method, with the exception of* {@code getBeanNamesForType} and {@code getBeansOfType} which will check* such manually registered singletons too. Of course, BeanFactory's {@code getBean}* does allow transparent access to such special beans as well. However, in typical* scenarios, all beans will be defined by external bean definitions anyway, so most* applications don't need to worry about this differentiation.** <p><b>NOTE:</b> With the exception of {@code getBeanDefinitionCount}* and {@code containsBeanDefinition}, the methods in this interface* are not designed for frequent invocation. Implementations may be slow.*/
public interface ListableBeanFactory extends BeanFactory {

上述源码注释则是说明了基础的beanFactory只能一个一个获取bean对象而不能一次性获取多个,因此ListableBeanFactory则解决了这一问题,同时对于一些底层bean则是不对外提供获取方式,因为这些bean只是在beanFactory内部使用的

能力BeanFactoryListableBeanFactory
按名称获取单个 Bean✅ getBean("name")✅ 支持
获取所有 Bean 名称✅ getBeanDefinitionNames()
按类型获取多个 Bean✅ getBeansOfType()
按注解获取 Bean✅ getBeansWithAnnotation()
获取 Bean 定义数量✅ getBeanDefinitionCount()

AutowireCapableBeanFactory

AutowireCapableBeanFactory 是 Spring 框架中 BeanFactory 的高级扩展接口,核心作用是提供程序化控制 Bean 创建、依赖注入和初始化的能力。它使开发者能够在 Spring 容器之外手动管理 Bean 的生命周期,特别适用于框架集成和高级定制场景。

功能方法示例应用场景
手动创建 Bean 实例T createBean(Class<T> beanClass)动态创建未注册的 Bean
手动依赖注入void autowireBean(Object existingBean)对现有对象进行依赖注入
执行完整生命周期Object initializeBean(Object existingBean, String beanName)触发初始化回调(@PostConstructInitializingBean
应用后置处理器Object applyBeanPostProcessorsBeforeInitialization(Object bean, String name)手动触发 BeanPostProcessor 逻辑
解析依赖关系Object resolveDependency(DependencyDescriptor descriptor, String beanName)解决特定依赖(如带 @Autowired 的字段)

AutowireCapableBeanFactory 是 Spring 容器的底层操作接口,它提供以下核心价值:

  1. 程序化控制:手动控制 Bean 的生命周期(创建 → 注入 → 初始化)

  2. 容器外集成:为不受 Spring 管理的对象提供依赖注入能力

  3. 框架扩展点:支持与其他框架深度集成

  4. 高级定制:动态创建和配置特殊场景需要的 Bean

推荐使用场景不推荐场景
框架集成(JPA, JMS 等)常规业务逻辑开发
动态对象创建(如反射场景)替代 @Autowired 的标准注入
遗留代码改造需要容器完整管理的 Bean
单元测试中模拟 Spring 容器行为需要作用域管理的 Bean(如 request)

AbstractAutowireCapableBeanFactory

AbstractAutowireCapableBeanFactory是 Spring 框架中实现 Bean 创建、依赖注入和初始化的核心抽象基类,它在 Spring IoC 容器体系中扮演着至关重要的角色。

上图则是有关AbstractAutowireCapableBeanFactory的层次结构,而AbstractAutowireCapableBeanFactory则是负责bean的生命周期的管理,bean的创建,依赖注入,销毁。这些阶段都在本类中的方法中执行。

AbstractAutowireCapableBeanFactory 是 Spring IoC 容器的引擎核心,其核心价值在于:

  1. 生命周期管理:标准化 Bean 的创建 → 注入 → 初始化 → 销毁流程

  2. 扩展性设计:通过模板方法模式和 BeanPostProcessor 支持深度定制

  3. 依赖解析:实现各种自动装配策略(byName/byType/constructor)

  4. 基础支撑:为高级容器(如 ApplicationContext)提供底层 Bean 管理能力

DefaultListableBeanFactory

DefaultListableBeanFactory则是目前默认使用的beanFactory

  • 基础实现:作为BeanFactory接口的默认实现,它是Spring IoC容器的核心基础组件

  • 功能整合:继承了AbstractAutowireCapableBeanFactory并实现了ConfigurableListableBeanFactoryBeanDefinitionRegistry等关键接口,整合了以下能力:

    • Bean定义注册(BeanDefinitionRegistry

    • 依赖解析(ListableBeanFactory

    • 生命周期管理(AutowireCapableBeanFactory

    • 单例管理(SingletonBeanRegistry)。

  • 广泛应用:无论是传统的XML配置(如XmlBeanFactory)还是现代注解驱动的ApplicationContext(如AnnotationConfigApplicationContext),其底层均委托DefaultListableBeanFactory处理Bean的注册与加载

尽管开发者通常直接使用ApplicationContext(如Spring Boot中的AnnotationConfigApplicationContext),但其内部仍依赖DefaultListableBeanFactory实现核心功能:

  • ApplicationContext的底层委托:高级容器通过组合模式将Bean管理逻辑委托给DefaultListableBeanFactory36。

  • 功能扩展对比

    功能ApplicationContextDefaultListableBeanFactory
    Bean延迟加载默认立即初始化单例支持延迟加载
    国际化支持
    事件发布
    AOP集成内置支持需手动注册后处理器
http://www.dtcms.com/a/315445.html

相关文章:

  • day 46 神经网络-简版
  • 2025年渗透测试面试题总结-01(题目+回答)
  • 什么是压接孔?压接孔PCB制造流程
  • Zabbix 企业级高级应用
  • AI赋能复合材料与智能增材制造:前沿技术研修重磅
  • 【MATLAB】(八)矩阵
  • 盟接之桥说制造:价格战与品质:制造企业可持续发展的战略思考
  • 智能融合:增材制造多物理场AI建模与工业应用实战
  • PHP:历经岁月仍熠熠生辉的服务器端脚本语言
  • Spring 的 ioc 控制反转
  • 无人设备遥控器之信号切换技术篇
  • Guava 与 Caffeine 本地缓存系统详解
  • jQuery DOM节点操作详解
  • stm32F407 硬件COM事件触发六步换相
  • AI医疗革命:十大应用场景如何重塑未来医疗
  • 手绘风格制图新选择:如何用Excalidraw+cpolar构建你的视觉化工作流?
  • windos10 安装CentOS7 虚拟机笔记
  • Datawhale AI夏令营 第三期 task2
  • 基于ZYNQ ARM+FPGA的声呐数据采集系统设计
  • 01数据结构-平衡二叉树
  • Prometheus监控学习-安装
  • 【Git】实现使用SSH方式连接远程仓库时的免密操作
  • 计算机网络:目的网络在路由表项中的作用
  • Python实战项目--学生成绩管理系统
  • 机器人slam个人笔记
  • 交叉验证:机器学习模型评估的“稳压器”——从原理到实战
  • 测试开发:Python+Django实现接口测试工具
  • AI 对话高效输入指令攻略(四):AI+Apache ECharts:生成各种专业图表
  • 第六章 道阻且艰(2025.7学习总结)
  • 期权定价全解析:从Black-Scholes到量子革命的金融基石