# 控制反转

**控制反转**（Inversion of Control，IoC）是软件工程中的一个广义设计理念，指将对程序行为某一方面的控制权从应用代码转移给框架或容器。一种常见形式是框架在它决定的时机调用应用代码，而非应用去调用库函数。马丁·福勒（Martin Fowler）于2004年将特定的容器模式命名为依赖注入，他将这一现象描述为“它调用我，而不是我调用框架”，亦称好莱坞原则——“别打给我们，我们会打给你。”<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 什么被反转了 | 在普通调用中，A调用B并控制时机；在IoC下，B一旦获得A的标识符，便掌控时机并调用A，如同回调。<sup>[2](https://alistaircockburn.com/Discussion%20of%20dependency%20inversion%20etc.pdf)</sup> |
| 框架与库 | IoC是区分框架与库的关键所在：库是供客户端调用的一组函数，每次调用后控制权回到客户端。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup> |
| 主要DI风格 | 构造器注入、设值注入和接口注入。<sup>[3](https://martinfowler.com/articles/injection.html)</sup> |
| 容器启动开销 | 在一项Java基准测试中，手工装配（“Vanilla”）图启动耗时3毫秒，Dagger为46毫秒，Guice为458毫秒，带注解扫描的Spring为22,302毫秒。<sup>[4](https://github.com/greenlaw110/di-benchmark)</sup> |
| 服务定位器之争 | 福勒认为服务定位器与依赖注入同样易于打桩。<sup>[3](https://martinfowler.com/articles/injection.html)</sup> |
| 术语历史 | 该术语首次出现于约翰逊（Johnson）和富特（Foote）1988年的论文《设计可复用类》；好莱坞原则这一同义词可追溯至理查德·斯威特（Richard Sweet）1983年关于施乐Mesa系统的论文；福勒于2004年1月定名“依赖注入”。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup><sup> • </sup><sup>[3](https://martinfowler.com/articles/injection.html)</sup> |
| 编译期DI | Metro Kotlin编译器插件报告称，从Dagger配合Anvil和KAPT/KSP迁移后，构建时间改善50%至80%。<sup>[5](https://www.zacsweers.dev/metro-is-stable/)</sup> |

## 定义与核心思想

“反转”在于谁控制调用的时机。在普通调用序列中，A调用B来提供某项服务，A掌控调用时机；在反转情形下，B一旦获得A的标识符，便掌控时机并调用A，这正是回调的结构。<sup>[2](https://alistaircockburn.com/Discussion%20of%20dependency%20inversion%20etc.pdf)</sup>科伯恩（Cockburn）以此作为该术语的一般性解释。

**框架与库。** 使用库时，客户端代码调用库的函数，每次调用后控制权回到客户端。使用框架时，框架调用开发者的代码；福勒称IoC是使框架区别于库的关键所在。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup>卡内基梅隆大学一项关于框架的调查指出，好莱坞原则一直被视为框架的定义性机制，因为它体现了控制反转。<sup>[6](http://www.cs.cmu.edu/afs/cs/Web/People/kbierhof/papers/frameworks.pdf)</sup>[维也纳大学](https://www.edgepedia.org/zh/university-of-vienna)的一项学术论述给出了其一般形式：控制反转意味着框架接管对应用所描述行为的控制，至少是部分地、以明确定义的方式接管。<sup>[7](https://eprints.cs.univie.ac.at/2822/1/Inversion-of-Control_Layer.pdf)</sup>

## 机制与形式

IoC以若干具体形式出现：

- **模板方法。** 在JUnit中，框架调用`setUp`和`tearDown`方法来创建和清理测试夹具；框架发起调用，用户代码做出响应，因此控制被反转了。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup>
- **回调与事件驱动框架。** 向系统注册回调、由系统稍后调用，这是最初的形式；施乐开发环境的Tajo窗口系统允许工具开发者向整体窗口与执行系统注册回调过程。<sup>[7](https://eprints.cs.univie.ac.at/2822/1/Inversion-of-Control_Layer.pdf)</sup>
- **依赖注入。** Spring的文档将DI定义为IoC的一种特殊形式：对象仅通过构造器参数、工厂方法参数或构造后在对象实例上设置的属性来定义其依赖，容器在创建bean时注入这些依赖；这一过程从根本上说是bean自身控制其依赖的实例化或定位的逆过程。<sup>[8](https://docs.spring.io/spring-framework/reference/core/beans/introduction.html)</sup>福勒命名了三种风格：构造器注入、设值注入和接口注入。<sup>[3](https://martinfowler.com/articles/injection.html)</sup>
- **服务定位器。** 在定位器方式下，应用类向定位器发送显式请求以获取服务；而在注入方式下，不发出此类请求——服务直接出现在应用类中，这就是为什么说控制被反转了。<sup>[3](https://martinfowler.com/articles/injection.html)</sup>

Stack Overflow上一个高票回答总结了二者的关系：依赖注入是IoC模式更具体的版本，其中实现通过构造器或设值方法传入对象。<sup>[9](https://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection)</sup>

## 依赖注入容器

依赖注入容器可执行三项工作：绑定的注册、依赖图的解析以及生命周期管理。

**注册与解析。** .NET将依赖注入编织进了框架本身，并附带一个默认容器`IServiceProvider`；通常的做法是在应用启动时通过将服务添加到`IServiceCollection`来注册服务，所有服务添加完毕后，由`BuildServiceProvider`构造容器。框架承担创建依赖实例的责任，并在不再需要时将其释放。<sup>[10](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/overview)</sup>

**生命周期作用域。** .NET服务可按三种生存期注册：瞬态服务每次从容器请求时都会创建；对于Web应用，作用域生存期表示每个客户端请求（连接）创建一次服务；单例服务的每次后续请求都使用同一实例。微软警告不要通过构造器注入直接从单例解析作用域服务，因为作用域实例的存活时间将超出其预期生存期。<sup>[11](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes)</sup>

Spring的`ApplicationContext`对bean扮演同样的角色，其AOT支持在构建时检查该上下文，以应用通常发生在运行时的决策和发现逻辑。<sup>[12](https://docs.spring.io/spring/reference/6.2-SNAPSHOT/core/aot.html)</sup>

## 数据一览

**启动与查找开销。** di-benchmark套件测量容器启动加上首次获取和重复查找。启动加首次获取：Vanilla启动3毫秒、获取5毫秒，Feather为8毫秒和73毫秒，Dagger为46毫秒和130毫秒，Guice为458毫秒和800毫秒，Java配置的Spring为13,956毫秒和1,149毫秒，注解扫描的Spring为22,302毫秒和2,738毫秒。<sup>[4](https://github.com/greenlaw110/di-benchmark)</sup>运行时查找呈现同样的分布：获取新bean 50,000次，Vanilla耗时3毫秒，Dagger 28毫秒，Guice 188毫秒，SpringAnnotationScanned 2,369毫秒；获取单例5,000,000次，Vanilla耗时5毫秒，Guice 559毫秒，Feather 180毫秒，Dagger 746毫秒，SpringAnnotationScanned 228毫秒。<sup>[4](https://github.com/greenlaw110/di-benchmark)</sup>

**占用空间。** 另一项独立比较测量了含依赖的jar大小与执行时间：Dagger 58 KB、90毫秒，Cayenne DI 71 KB、105毫秒，Guice 3,827 KB、204毫秒，Spring 4,800 KB、221毫秒，[Spring Boot](https://www.edgepedia.org/zh/spring-boot) 10,094 KB、743毫秒；OpenWebBeans记录为失败。<sup>[13](https://github.com/andrus/di-comparison)</sup>

**编译型容器与动态容器。** 一项PHP基准测试区分了编译型容器与动态容器：前者为生产使用生成一个类，使依赖图在构建时解析；后者即时解析依赖图。编译通常产生非常快的容器，因为使用容器时无需反射或配置；测试在原型或单例作用域下、规模为100、1或1,000个对象的对象图上进行。<sup>[14](https://kocsismate.github.io/php-di-container-benchmarks/benchmark.html)</sup>

**耦合与可测试性研究。** 一项对[SourceForge](https://www.edgepedia.org/zh/sourceforge)上20对开源项目的实证研究发现，依赖注入的使用与耦合和内聚数值之间没有相关性，不过在依赖注入计数达到10%或以上的项目中出现了耦合降低的趋势。<sup>[15](https://dl.acm.org/doi/10.5555/1647636.1647639)</sup>一项关于Web服务应用的研究报告称，基于DI的应用可测试性和可维护性远高于其他应用，并对收益与成本进行了定量分析。<sup>[16](https://dl.acm.org/doi/10.5555/2011304.2011308)</sup>一项2022年的研究提出了DI加权耦合度量（DCE和DCBO），并报告称使用[Spring框架](https://www.edgepedia.org/zh/spring-framework)的XML DI引入了少量耦合开销，会在小型项目中增加CBO，但仍允许通过配置替换类而无需更改代码。<sup>[17](https://www.mdpi.com/2073-431X/11/9/141)</sup>

## 服务定位器与替代方案

对服务定位器模式的主要批评在于，依赖通过通用的`GetService()`调用来解析，编译期无法保证该依赖曾被注册，因此程序可能在运行时失败。<sup>[18](https://www.toptal.com/developers/full-stack/exploring-dependency-injection-patterns)</sup>注入则使依赖可见：开发者查看构造器即可立刻看到类的依赖，而定位器则需要在源代码中搜索定位器调用，且定位器的每个使用者都依赖于定位器本身。<sup>[18](https://www.toptal.com/developers/full-stack/exploring-dependency-injection-patterns)</sup><sup> • </sup><sup>[3](https://martinfowler.com/articles/injection.html)</sup>

福勒认为，在解耦方面依赖注入与服务定位器实际上没有区别：两者都非常易于打桩，而声称DI使测试更容易的说法通常反映的是设计不佳的服务定位器。他建议对在单一应用内使用的类采用服务定位器，对打算跨多个应用使用的类采用依赖注入，并指出接口注入侵入性更强，这也是轻量级容器青睐设值注入和构造器注入的原因。<sup>[3](https://martinfowler.com/articles/injection.html)</sup>

IoC还与两个不同层面的同级概念并列：IoC是将主动权从被调用方交给框架的一般风格，比DI更广，包括回调和模板方法；DI是从外部传入依赖的一种实现技术；[依赖倒置原则](https://www.edgepedia.org/zh/dependency-inversion-principle)（DIP）则是关于依赖方向的源代码设计原则，除非抽象属于更高层一侧，否则什么都没有被倒置。<sup>[19](https://notes.rewheel.dev/en/docs/clean-code/solid-deep-dive/dip-di-and-ioc)</sup>《系统与软件杂志》上的一篇分类论文指出，依赖注入建立在两条设计原则之上：依赖倒置原则（马丁，1996）和控制反转（福勒，2004）。<sup>[20](https://www.sciencedirect.com/science/article/pii/S0164121221002223)</sup>

## 收益与批评

**有据可查的收益。** 基于构造器的注入让开发者能立即看到类的依赖，并可通过用依赖的模拟对象构造被测对象来实现单元测试。<sup>[18](https://www.toptal.com/developers/full-stack/exploring-dependency-injection-patterns)</sup>Web服务研究发现DI应用更易于测试和维护。<sup>[16](https://dl.acm.org/doi/10.5555/2011304.2011308)</sup>通过配置替换实现而无需更改代码，这在Spring XML实验中有据可查。<sup>[17](https://www.mdpi.com/2073-431X/11/9/141)</sup>

**有据可查的成本。** 福勒警告说控制反转难以理解，会在调试时导致问题，因此总体而言除非需要，他宁愿避免使用。<sup>[3](https://martinfowler.com/articles/injection.html)</sup>用反射或动态编程实现的DI框架可能妨碍IDE自动化，如引用查找、调用层次显示和安全重构。<sup>[17](https://www.mdpi.com/2073-431X/11/9/141)</sup>反射会拖慢应用启动，因为框架可能需要扫描模块、解析依赖图并反射式构造对象；带注解预处理器的Dagger 2是一个例外。<sup>[18](https://www.toptal.com/developers/full-stack/exploring-dependency-injection-patterns)</sup>上述测得的启动成本——从手工装配的3毫秒到注解扫描Spring的超过22秒——量化了这一代价。<sup>[4](https://github.com/greenlaw110/di-benchmark)</sup>

## 历史

控制反转一词首次出现于拉尔夫·约翰逊（Ralph Johnson）和布莱恩·富特（Brian Foote）的论文《设计可复用类》，由《面向对象编程杂志》于1988年发表，该文从基于抽象类的设计角度讨论了这一概念。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup><sup> • </sup><sup>[7](https://eprints.cs.univie.ac.at/2822/1/Inversion-of-Control_Layer.pdf)</sup>更生动的同义词好莱坞原则似乎起源于理查德·斯威特1983年关于施乐Mesa系统的论文，其中工具开发者向Tajo窗口系统注册回调过程。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup><sup> • </sup><sup>[7](https://eprints.cs.univie.ac.at/2822/1/Inversion-of-Control_Layer.pdf)</sup>该术语也出现在“四人帮”的设计模式书中，约翰·弗里赛德斯（John Vlissides）在《C++报告》专栏中以好莱坞原则之名对其进行了解释。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup>

PicoContainer的历史页面将术语的流行归功于斯特凡诺·马佐基（Stefano Mazzocchi），他在1998年设计后来成为Apache Avalon的Java Apache Server Framework时推广了该词，并指出这一概念此前已作为[鲍勃·马丁](https://www.edgepedia.org/zh/bob-martin)（Bob Martin）的依赖倒置原则和好莱坞原则被讨论过，该术语自1996年以来不断出现。<sup>[21](http://picocontainer.com/inversion-of-control-history.html)</sup>马丁1996年的DIP论文描述了传统结构化方法中子程序层次的目标，即高层模块调用低层模块，而他的原则反转了这种依赖结构。<sup>[22](https://www.cs.utexas.edu/~downing/papers/DIP-1996.pdf)</sup>2004年1月，福勒写道，控制反转一词过于宽泛，令人困惑，因此在与多位IoC倡导者讨论后，为轻量级容器所使用的特定模式定名为依赖注入。<sup>[3](https://martinfowler.com/articles/injection.html)</sup>福勒还告诫不要将一般原则与特定容器风格混为一谈，并指出EJB使用控制反转的程度丝毫不亚于那些与之对立的轻量级容器。<sup>[1](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup>

## 近期发展

**AOT与原生编译。** GraalVM原生镜像要求预先知道反射访问，除非明确指定，否则类路径资源不会包含在原生镜像中。Spring的AOT支持通过在构建时检查ApplicationContext并应用通常发生在运行时的决策和发现逻辑来应对，生成固定、受限的应用布置。<sup>[12](https://docs.spring.io/spring/reference/6.2-SNAPSHOT/core/aot.html)</sup>

**编译期依赖注入。** Metro是一个完全作为Kotlin编译器插件实现的Kotlin DI框架（分析用FIR，类头代码生成用FIR，其他所有代码生成用IR，没有KSP或KAPT源生成阶段），已达到稳定状态，有公司报告称从Dagger加Anvil加KAPT/KSP迁移后构建时间改善50%至80%。它执行完整的图验证、循[环检测](https://www.edgepedia.org/zh/cycle-detection)和作用域验证，没有运行时DI机制：无反射、无哈希表查找、无服务定位器、无全局模块注册表。<sup>[5](https://www.zacsweers.dev/metro-is-stable/)</sup>Koin增加了一个编译器插件，在构建过程中验证依赖图，将缺失依赖、限定符不匹配和跨作用域违规捕获为构建错误；其运行时解析仍是直接的`HashMap.get()`调用，无反射，兼容R8/ProGuard。<sup>[23](https://blog.insert-koin.io/koin-compiler-1-0-dsl-and-annotations-koin-now-compile-safe-06905a2b04ad)</sup>

## References

1. [Inversion Of Control (bliki), Martin Fowler](https://www.martinfowler.com/bliki/InversionOfControl.html)
2. [Discussion of Dependency Inversion, Dependency Injection, Dependency Lookup, Configurable Receiver and Inversion of Control, Alistair Cockburn](https://alistaircockburn.com/Discussion%20of%20dependency%20inversion%20etc.pdf)
3. [Inversion of Control Containers and the Dependency Injection pattern, Martin Fowler (January 2004)](https://martinfowler.com/articles/injection.html)
4. [di-benchmark, greenlaw110 (GitHub)](https://github.com/greenlaw110/di-benchmark)
5. [Metro is Stable, Zac Sweers](https://www.zacsweers.dev/metro-is-stable/)
6. [Frameworks on the Rise, Bierhoff et al., Carnegie Mellon University](http://www.cs.cmu.edu/afs/cs/Web/People/kbierhof/papers/frameworks.pdf)
7. [Inversion-of-Control Layer, University of Vienna](https://eprints.cs.univie.ac.at/2822/1/Inversion-of-Control_Layer.pdf)
8. [Introduction to the Spring IoC Container and Beans, Spring Framework documentation](https://docs.spring.io/spring-framework/reference/core/beans/introduction.html)
9. [Inversion of Control vs Dependency Injection, Stack Overflow](https://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection)
10. [Dependency injection - .NET, Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/overview)
11. [Service lifetimes - .NET, Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes)
12. [Ahead of Time Optimizations, Spring Framework documentation](https://docs.spring.io/spring/reference/6.2-SNAPSHOT/core/aot.html)
13. [di-comparison, andrus (GitHub)](https://github.com/andrus/di-comparison)
14. [DI Container Benchmark Results (PHP), kocsismate](https://kocsismate.github.io/php-di-container-benchmarks/benchmark.html)
15. [Effects of dependency injection on maintainability, IASTED SE&A 2008 (ACM)](https://dl.acm.org/doi/10.5555/1647636.1647639)
16. [Empirically assessing the impact of dependency injection on the development of web service applications (ACM)](https://dl.acm.org/doi/10.5555/2011304.2011308)
17. [Measuring Impact of Dependency Injection on Software Maintainability, Computers (MDPI, 2022)](https://www.mdpi.com/2073-431X/11/9/141)
18. [Inversion of Control Patterns, Toptal engineering blog](https://www.toptal.com/developers/full-stack/exploring-dependency-injection-patterns)
19. [The dependency inversion principle: DIP, DI and IoC, notes.rewheel.dev](https://notes.rewheel.dev/en/docs/clean-code/solid-deep-dive/dip-di-and-ioc)
20. [Cataloging dependency injection anti-patterns in software systems, Journal of Systems and Software](https://www.sciencedirect.com/science/article/pii/S0164121221002223)
21. [Inversion of Control History, PicoContainer](http://picocontainer.com/inversion-of-control-history.html)
22. [The Dependency Inversion, Robert C. Martin (1996)](https://www.cs.utexas.edu/~downing/papers/DIP-1996.pdf)
23. [Koin Compiler 1.0: DSL and Annotations, Koin now compile-safe, Koin blog](https://blog.insert-koin.io/koin-compiler-1-0-dsl-and-annotations-koin-now-compile-safe-06905a2b04ad)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software design and architecture › Titles 4 to Mo

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/inversion-of-control

English original: https://www.edgepedia.org/inversion-of-control
