由于掘金文章存在字数限制,本文拆开了各个章节分开发布,全文可点击以下链接进行阅读:blog.omghaowan.com/archives/sp…
IoC,全称Inversion of Control,即控制反转。相较于传统编程模式,IoC实现了对控制流的反转,即:
- 传统编程模式: 用户代码 -> 库/框架 -> 用户代码。对于传统编程模式,每次调用库/框架时都会将控制权从用户代码转移到库/框架中,然后库/框架在执行结束后再将控制权返回到用户代码。
IoC编程模式: 库/框架 -> 用户代码 -> 库/框架。对于IoC编程模式,一般我们会将我们的行为类插入到库/框架中,库/框架则会在相应的执行点将控制权转移到用户代码,然后用户代码在执行结束后再将控制权返回到库/框架。
在Spring文档是这样阐述的:
It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.
大致意思就是:对象通过构造参数、Factory方法参数或Setter方法参数指定的依赖项,容器会在后面bean创建的时候进行注入(通过使用类的直接构造或类似于服务定位器模式的机制来控制其依赖项的实例化或位置),这基本反转了bean的创建流程(因此得名,控制反转)。
正因为此,IoC也被称为dependency injection(DI),即依赖注入。但是严格来说它们并不等价,DI仅仅是IoC众多实现方式中的一种,它的实现方式还包括回调(callbacks)、调度程序(schedulers)、事件循环(event loops)和模板方法(the template method)等。
总的来说,所谓IoC控制反转就是,"it calls me rather me calling the framework"。
IoC一词并非起源于Spring,而是起源于1988年《Object-Oriented Programming》杂志中Johnson和Foote的一篇论文《Designing Reusable Classes》。关于
IoC、DI等更多详情可以阅读以下资料: