当前位置:网站首页>什么是依赖注入(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 将被调用者对象注入调用者对象
边栏推荐
- As we media, what websites are there to download video clips for free?
- 磁盘监控相关命令
- Is it necessary to renew the PMP certificate?
- Y58. Chapter III kubernetes from entry to proficiency - continuous integration and deployment (Sany)
- 说一说MVCC多版本并发控制器?
- JHOK-ZBG2漏电继电器
- Simulate thread communication
- 导航栏根据路由变换颜色
- 利用OPNET进行网络任意源组播(ASM)仿真的设计、配置及注意点
- SQL injection HTTP header injection
猜你喜欢
U++ metadata specifier learning notes
c语言神经网络基本代码大全及其含义
EGR-20USCM接地故障继电器
Auto. JS get all app names of mobile phones
JVM(二十) -- 性能监控与调优(一) -- 概述
Under the trend of Micah, orebo and apple homekit, how does zhiting stand out?
Window scheduled tasks
照片选择器CollectionView
Pytest testing framework -- data driven
A cool "ghost" console tool
随机推荐
DOM-节点对象+时间节点 综合案例
导航栏根据路由变换颜色
Window scheduled tasks
Safe landing practice of software supply chain under salesforce containerized ISV scenario
DBSync新增对MongoDB、ES的支持
NPDP产品经理认证,到底是何方神圣?
Initial experience of annotation
AIDL 与Service
基于 hugging face 预训练模型的实体识别智能标注方案:生成doccano要求json格式
Most commonly used high number formula
利用OPNET进行网络仿真时网络层协议(以QoS为例)的使用、配置及注意点
Operand of null-aware operation ‘!‘ has type ‘SchedulerBinding‘ which excludes null.
【问道】编译原理
Phenomenon analysis when Autowired annotation is used for list
最长回文子串(动态规划)
Senior programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization, and recommends collecting
JVM(二十) -- 性能监控与调优(一) -- 概述
阿里云的神龙架构是怎么工作的 | 科普图解
Timer create timer
拿到PMP认证带来什么改变?