什么是Spring框架中的依赖注入和控制反转? [英] What is Dependency Injection and Inversion of Control in Spring Framework?
问题描述
任何人都可以解释它是什么
- Spring有助于创建松散耦合的应用程序,因为依赖注入。
- 在spring对象定义它们的关联(依赖关系),不用担心如何获得依赖关系现在,Spring负责提供创建对象所需的依赖关系。
例如:假设我们有一个对象Employee,它对对象地址有依赖关系。
所以我们定义一个对应于Employee的bean,它将定义它对对象Address的依赖。
当Spring尝试创建一个Object Employee时,它会看到Employee对对象Address
有依赖关系,所以首先它将创建Address对象(依赖对象),然后将其注入Employee Object。
-
使用反向控制(IOC)和依赖注入(DI)互换。 IOC是通过DI实现的。 DI是提供相关性的过程,IOC是DI的最终结果(注意: DI不是实现IOC的唯一方法,有其他方式)。
-
由DI负责创建对象从我们的应用程序代码转移到Spring容器,因此现象称为IOC。
- 依赖注入可以通过setter注入,构造函数注入来完成。
"Dependency Injection" and "Inversion of Control" are often mentioned as the primary advantages of using the Spring framework for developing Web frameworks
Could anyone explain what it is in very simple terms with an example if possible?
- Spring helps in creating loosely coupled application because of Dependency Injection.
- In spring objects define their associations (dependencies) and do not worry about how to get those dependencies ; now it is the responsibility of Spring to provide the required dependencies for creating objects.
For example : Suppose we have an object Employee and it has a dependency on object Address. So we define a bean corresponding to Employee where it will define its dependency on object Address. When Spring try to create an Object Employee it sees that Employee has a dependency on object Address so first it will create the Address object (dependent object) and then inject this into the Employee Object.
Inversion of Control (IOC) and Dependency Injection (DI) are used interchangeably. IOC is achieved through DI. DI is the process of providing the dependencies and IOC is the end result of DI (Note: DI is not the only way to achieve IOC, there are other ways as well).
By DI the responsibility of creating objects is shifted from our application code to Spring container hence the phenomenon is called IOC.
- Dependency Injection can be done by setter injection, constructor injection.
这篇关于什么是Spring框架中的依赖注入和控制反转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!