Spring(Spring Framework)的原生启动过程,它主要涉及 ApplicationContext
的初始化、BeanFactory 的加载、Bean 的创建与依赖注入。下面详细解析:
Spring 原生启动过程
Spring 本身不依赖 SpringApplication
,其核心在于 ApplicationContext
的创建与管理。通常,Spring 通过 ClassPathXmlApplicationContext
或 AnnotationConfigApplicationContext
启动。以下是基于 AnnotationConfigApplicationContext
(基于注解的 Spring 容器)的启动过程:
1. 创建 ApplicationContext
Spring 应用的启动通常由 ApplicationContext
实例化开始,例如:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
主要做了:
- 初始化
AnnotationConfigApplicationContext
- 创建
BeanFactory
- 注册
AppConfig
作为配置类
2. 扫描 & 注册 Bean
Spring 通过 BeanDefinitionReader
解析 @ComponentScan
或 XML 配置:
- 解析
@ComponentScan
扫描包路径 - 解析
@Bean
方法 - 将所有 Bean 的元信息存入
BeanDefinitionRegistry
(Bean 定义注册表)
3. 创建 BeanFactory
Spring 内部使用 DefaultListableBeanFactory
作为 Bean 容器:
BeanFactory
仅存储 Bean 定义(BeanDefinition
),此时 Bean 还未实例化BeanDefinition
记录了 Bean 的构造方法、依赖信息、作用域(singleton
/prototype
)等
4. 处理 BeanFactoryPostProcessor
在 Bean 还未实例化之前,Spring 允许 BeanFactoryPostProcessor
修改 Bean 的定义,比如:
PropertySourcesPlaceholderConfigurer
解析${}
占位符ConfigurationClassPostProcessor
解析@Configuration
、@Bean
5. 实例化 & 依赖注入(DI)
当所有 Bean 定义处理完毕后,Spring 开始创建 Bean:
- 实例化单例 Bean
- 通过 构造方法 或 工厂方法 创建对象
- 依赖注入
- 解析
@Autowired
、@Resource
- 解析
@Value
注入配置值
- 解析
- 调用
BeanPostProcessor
进行 AOP 等增强@PostConstruct
方法执行- 如果有 AOP,Spring 会为 Bean 创建代理对象
6. 发布事件 & 启动完成
Spring 容器启动完成后:
- 发布
ContextRefreshedEvent
- 调用
ApplicationListener
- Spring 进入运行状态
如果你是基于 Spring 传统 XML 配置的启动,过程类似,但 ClassPathXmlApplicationContext
读取的是 XML 而不是 @Configuration
类。