IoC 容器 (The IoC Container)
本章详细介绍了 Spring 的控制反转 (IoC) 容器。
章节概览 (Section Summary)
- Spring IoC 容器和 Bean 简介
- Introduction to the Spring IoC Container and Beans
- 容器概览
- Container Overview
- Bean 概览
- Bean Overview
- 依赖注入 (Dependencies)
- Dependencies
- Bean 作用域 (Scopes)
- Bean Scopes
- 自定义 Bean 的性质
- Customizing the Nature of a Bean
- Bean 定义继承
- Bean Definition Inheritance
- 容器扩展点
- Container Extension Points
- 基于注解的容器配置
- Annotation-based Container Configuration
- 类路径扫描与组件管理
- Classpath Scanning and Managed Components
- 使用 JSR 330 标准注解
- Using JSR 330 Standard Annotations
- 基于 Java 的容器配置
- Java-based Container Configuration
- 环境抽象 (Environment Abstraction)
- Environment Abstraction
- 注册 LoadTimeWeaver
- Registering a LoadTimeWeaver
- ApplicationContext 的额外功能
- Additional Capabilities of the ApplicationContext
- BeanFactory API
- The BeanFactory API
补充教学 —— 理解 IoC 容器的本质
1. 什么是 IoC (控制反转)? 在没有 IoC 之前,如果你在一个类里需要另一个对象,你会通过 new 关键字亲自去“控制”它的创建。 有了 IoC 之后,权力和职责发生了“反转”:你不再负责找对象,而是配置好你需要什么,由容器(管家)在运行时把对象“注入”给你。
2. 为什么叫“容器”? 因为它不仅仅是创建一个对象,它还负责:
- 生命周期管理:对象什么时候创建(懒加载还是立即加载)?什么时候销毁?
- 依赖管理:我有 A,A 依赖 B,容器会帮你自动关联好。
- 配置中心:所有的对象关系都由容器统一保管。
3. ApplicationContext vs BeanFactory 这是初学者最容易混淆的两个概念:
- BeanFactory:是 Spring 的心脏,提供了最基础依赖注入功能。
- ApplicationContext:是 BeanFactory 的子接口,它不仅拥有 BeanFactory 的所有功能,还增加了国际化、事件发布、资源加载等企业级功能。在绝大多数情况下,我们直接使用 ApplicationContext。
4. 学习建议 IoC Container 是整个 Spring 框架的基座。如果你觉得内容太多,请优先攻克 “依赖注入 (Dependencies)” 和 “基于注解的容器配置”。理解了这两块,你就能上手开发 90% 的 Spring 业务了。