当前位置:网站首页>什么是依赖注入(DI)
什么是依赖注入(DI)
2022-07-06 23:34:00 【PIKapikaaaa】
DI的全称是Dependency Injection,中文称之为依赖注入。
它与控制反转(IoC)的含义相同,只不过这两个称呼是从两个角度描述的同一个概念。对于一个Spring初学者来说,这两种称呼很难理解,下面我们将通过简单的语言来描述这两个概念。
当某个Java对象(调用者)需要调用另一个Java对象(被调用者,即被依赖对象)时,在传统模式下,调用者通常会采用“new 被调用者”的代码方式来创建对象,如图1所示。这种方式会导致调用者与被调用者之间的耦合性增加,不利于后期项目的升级和维护。

图1 调用者创建被调用者对象
在使用Spring框架之后,对象的实例不再由调用者来创建,而是由Spring容器来创建,Spring容器会负责控制程序之间的关系,而不是由调用者的程序代码直接控制。这样,控制权由应用代码转移到了Spring容器,控制权发生了反转,这就是Spring的控制反转。
从Spring容器的角度来看,Spring容器负责将被依赖对象赋值给调用者的成员变量,这相当于为调用者注入了它依赖的实例,这就是Spring的依赖注入,如图2所示。

图2 将被调用者对象注入调用者对象
边栏推荐
- DFS, BFS and traversal search of Graphs
- 最长公共子序列(LCS)(动态规划,递归)
- 利用OPNET进行网络仿真时网络层协议(以QoS为例)的使用、配置及注意点
- 10 distributed databases that take you to the galaxy
- Use Zhiyun reader to translate statistical genetics books
- U++4 interface learning notes
- MySQL数据库学习(7) -- pymysql简单介绍
- [JS component] custom select
- 【opencv】图像形态学操作-opencv标记不同连通域的位置
- Vector and class copy constructors
猜你喜欢

高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏

Full link voltage test: the dispute between shadow database and shadow table
![[JS component] date display.](/img/26/9bfc752c8c9a933a8e33b59e0488a2.jpg)
[JS component] date display.

10 distributed databases that take you to the galaxy

y58.第三章 Kubernetes从入门到精通 -- 持续集成与部署(三一)

【js组件】date日期显示。
![[opencv] image morphological operation opencv marks the positions of different connected domains](/img/c3/f437bad9432dedbbb14c8a62ba5180.png)
[opencv] image morphological operation opencv marks the positions of different connected domains

Safe landing practice of software supply chain under salesforce containerized ISV scenario

MySQL数据库学习(8) -- mysql 内容补充

【opencv】图像形态学操作-opencv标记不同连通域的位置
随机推荐
【问道】编译原理
When deleting a file, the prompt "the length of the source file name is greater than the length supported by the system" cannot be deleted. Solution
How does redis implement multiple zones?
[JS component] custom select
利用OPNET进行网络单播(一服务器多客户端)仿真的设计、配置及注意点
Full link voltage test: the dispute between shadow database and shadow table
Under the trend of Micah, orebo and apple homekit, how does zhiting stand out?
与利润无关的背包问题(深度优先搜索)
利用OPNET进行网络仿真时网络层协议(以QoS为例)的使用、配置及注意点
Timer create timer
Array initialization of local variables
漏电继电器JOLX-GS62零序孔径Φ100
Development thoughts of adding new requirements in secondary development
If you‘re running pod install manually, make sure flutter pub get is executed first.
Timer创建定时器
Leetcode (46) - Full Permutation
Let f (x) = Σ x^n/n^2, prove that f (x) + F (1-x) + lnxln (1-x) = Σ 1/n^2
【QT】自定义控件-Loading
How can professional people find background music materials when doing we media video clips?
Leetcode (417) -- Pacific Atlantic current problem