当前位置:网站首页>什么是依赖注入(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 将被调用者对象注入调用者对象
边栏推荐
- window定时计划任务
- 【js组件】自定义select
- Safe landing practice of software supply chain under salesforce containerized ISV scenario
- 漏电继电器LLJ-100FS
- 局部变量的数组初始化问题
- [QT] custom control loading
- 张平安:加快云上数字创新,共建产业智慧生态
- [Oracle] simple date and time formatting and sorting problem
- QSlider of QT control style series (I)
- 高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
猜你喜欢

If you‘re running pod install manually, make sure flutter pub get is executed first.
![[JS component] date display.](/img/26/9bfc752c8c9a933a8e33b59e0488a2.jpg)
[JS component] date display.

利用OPNET进行网络单播(一服务器多客户端)仿真的设计、配置及注意点

Leetcode(46)——全排列

Leetcode (46) - Full Permutation

pmp真的有用吗?

Longest palindrome substring (dynamic programming)

Full link voltage test: the dispute between shadow database and shadow table

CentOS 7.9 installing Oracle 21C Adventures

Auto.js 获取手机所有app名字
随机推荐
1.AVL树:左右旋-bite
HarmonyOS第四次培训
Scheduledexecutorservice timer
Leetcode(417)——太平洋大西洋水流问题
创始人负债10亿,开课吧即将“下课”?
导航栏根据路由变换颜色
【js组件】自定义select
Mysql database learning (7) -- a brief introduction to pymysql
Phenomenon analysis when Autowired annotation is used for list
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
np. random. Shuffle and np Use swapaxis or transfer with caution
Leetcode (417) -- Pacific Atlantic current problem
DOM-节点对象+时间节点 综合案例
LinkedBlockingQueue源码分析-初始化
局部变量的数组初始化问题
JVM(十九) -- 字节码与类的加载(四) -- 再谈类的加载器
JVM (19) -- bytecode and class loading (4) -- talk about class loader again
Wonderful express | Tencent cloud database June issue
JVM (XX) -- performance monitoring and tuning (I) -- Overview
线程池的创建与使用