什么是 Spring Framework 中的依赖注入和控制反转? [英] What is Dependency Injection and Inversion of Control in Spring Framework?

查看:23
本文介绍了什么是 Spring Framework 中的依赖注入和控制反转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

依赖注入"和控制反转"经常被称为使用 Spring 框架开发 Web 框架的主要优势

"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 有助于创建松散耦合的应用程序.
  • 在 Spring 中,对象定义了它们的关联(依赖),而不用担心它们将如何获得这些依赖.Spring 负责为创建对象提供所需的依赖项.
    • Spring helps in the creation of loosely coupled applications because of Dependency Injection.
    • In Spring, objects define their associations (dependencies) and do not worry about how they will get those dependencies. It is the responsibility of Spring to provide the required dependencies for creating objects.
    • 例如:假设我们有一个对象Employee,它依赖于对象Address.我们将定义一个对应于 Employee 的 bean,它将定义它对对象 Address 的依赖.

      For example: Suppose we have an object Employee and it has a dependency on object Address. We would define a bean corresponding to Employee that will define its dependency on object Address.

      当 Spring 尝试创建 Employee 对象时,它会看到 EmployeeAddress 有依赖关系,因此它会首先创建Address 对象(依赖对象),然后将其注入到 Employee 对象中.

      When Spring tries to create an Employee object, it will see that Employee has a dependency on Address, so it will first create the Address object (dependent object) and then inject it into the Employee object.

      • 控制反转 (IoC) 和依赖注入 (DI) 可以互换使用.IoC 是通过 DI 实现的.DI是提供依赖的过程,IoC是DI的最终结果.(注意: DI 并不是实现 IoC 的唯一方法.还有 other方式.)

      • 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.)

      通过 DI,创建对象的责任从我们的应用程序代码转移到了 Spring 容器;这种现象称为 IoC.

      By DI, the responsibility of creating objects is shifted from our application code to the Spring container; this phenomenon is called IoC.

      这篇关于什么是 Spring Framework 中的依赖注入和控制反转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆