我们将围绕三个核心问题展开:
容器到底是什么?(本质、接口、实现类)
容器从哪来?怎么启动的?(生命周期入口)
容器管什么?怎么管的?(核心职责与内部结构)
一、容器到底是什么?
✅ 一句话定义:
Spring 容器 = 一个管理 Bean 生命周期和依赖关系的对象工厂(Object Factory) + 配置元数据的运行时上下文(Runtime Context)。
✅ 核心接口与实现:
接口/类
作用
说明
BeanFactory
最基础的容器接口
提供 getBean()、containsBean() 等核心方法,是 IoC 的底层基础
ApplicationContext
高级容器接口(我们日常用的)
继承 BeanFactory,额外支持:国际化、事件发布、资源加载、AOP 集成等
AnnotationConfigApplicationContext
基于注解的容器实现
用于纯 Java 配置(@Configuration、@ComponentScan)
GenericApplicationContext / DefaultListableBeanFactory
容器的“心脏”
实际存储 BeanDefinition 和单例 Bean 的地方
💡 你在 Spring Boot 中用的 SpringApplication.run(),最终创建的是 AnnotationConfigServletWebServerApplicationContext(Web 环境)或 AnnotationConfigApplicationContext(非 Web),它们都内部持有一个 DefaultListableBeanFactory。
二、容器从哪来?怎么启动的?
启动入口(以 Spring Boot 为例):
SpringApplication.run(MyApp.class, args);
这行代码背后做了什么?
创建 ApplicationContext 实例 → 根据是否 Web 环境,选择具体子类(如 AnnotationConfigServletWebServerApplicationContext)。
调用 refresh() 方法(容器启动的核心!) 这是所有 Spring 容器的统一启动协议,定义在 AbstractApplicationContext 中。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1. 准备刷新(设置启动时间、激活标志等