📜  Spring——控制反转和依赖注入的区别

📅  最后修改于: 2022-05-13 01:55:38.329000             🧑  作者: Mango

Spring——控制反转和依赖注入的区别

Spring 是一个开源轻量级框架,它允许Java EE 7 开发人员构建简单、可靠和可扩展的企业应用程序。该框架主要侧重于提供各种方法来帮助您管理业务对象。与Java数据库连接 (JDBC)、JavaServer Pages (JSP) 和Java Servlet 等经典Java框架和应用程序编程接口 (API) 相比,它使 Web 应用程序的开发更加容易。该框架使用各种新技术,如面向方面编程 (AOP)、普通Java对象 (POJO) 和依赖注入 (DI) 来开发企业应用程序。

Spring IoC(控制反转)

Spring IoC(控制反转)容器是 Spring Framework 的核心。它创建对象,配置和组装它们的依赖关系,管理它们的整个生命周期。容器使用依赖注入(DI)来管理组成应用程序的组件。它从配置文件 (XML) 或Java代码或Java注释和Java POJO 类中获取有关对象的信息。这些对象称为 Bean。由于Java对象及其生命周期的控制不是由开发人员完成的,因此称为控制反转。以下是 Spring IoC 的一些主要特性,

  • 为我们创建对象,
  • 管理我们的对象,
  • 帮助我们的应用程序可配置,
  • 管理依赖项

Spring 依赖注入

依赖注入是Spring IOC(Inversion of Control)提供的主要功能。 Spring-Core 模块负责通过 Constructor 或 Setter 方法注入依赖项。控制反转的设计原则强调保持Java类相互独立,容器将它们从对象创建和维护中解放出来。这些由 Spring 管理的类必须遵守 Java-Bean 的标准定义。 Spring 中的依赖注入还确保了类之间的松散耦合。 Spring 依赖注入有两种类型。

  1. Setter 依赖注入 (SDI)
  2. 构造函数依赖注入 (CDI)

A. Setter 依赖注入 (SDI)

Setter Injection 是两种依赖注入方法中更简单的一种。在此,依赖注入将在 setter 和/或 getter 方法的帮助下注入。现在要在 bean 中将 Dependency Injection 设置为 Setter Injection,它是通过 bean-configuration 文件完成的。为此,要使用 Setter Injection 设置的属性在 bean-config 文件中的标记下声明。

B. 构造函数依赖注入(CDI)

在构造函数注入中,依赖注入将在构造函数的帮助下被注入。现在要将依赖注入设置为bean中的构造函数依赖注入,它是通过bean配置文件完成的。为此,要使用 CDI 设置的属性在 bean-config 文件中的标记下声明。

最后,让我们通过下表描述它们之间的激烈差异,以便更好地理解,因为如果不深入理解,总会存在两难境地。

Spring IoC (Inversion of Control)

Spring Dependency Injection

Spring IoC Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle.Spring Dependency injection is a way to inject the dependency of a framework component by the following ways of spring: Constructor Injection and Setter Injection
Spring helps in creating objects, managing objects, configurations, etc. because of IoC (Inversion of Control). Spring framework helps in the creation of loosely-coupled applications because of Dependency Injection.
Spring IoC is achieved through Dependency Injection.Dependency Injection is the method of providing the dependencies and Inversion of Control is the end result of Dependency Injection.
IoC is a design principle where the control flow of the program is inverted.Dependency Injection is one of the subtypes of the IOC principle.  
Aspect-Oriented Programing is one way to implement Inversion of Control.In case of any changes in business requirements, no code change is required.

相关文章:

  • Spring 依赖注入与示例