Spring Dependency Injection 简明教程

Spring DI - Overview

Spring 是一个最受欢迎的应用程序开发框架,用于企业级 Java。全世界数百万开发人员使用 Spring Framework 创建高性能、易于测试的代码,可以重复使用。

Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code.

Spring Framework 是一个开源 Java 平台。它最初由 Rod Johnson 编写,并于 2003 年 6 月首次在 Apache 2.0 许可证下发布。

Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Spring 提供 Ioc 容器,与 EJB 容器相比,它们往往更轻量级。这对在具有受限内存和 CPU 资源的计算机上开发和部署应用程序非常有利。

Spring provides Ioc Containers which tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.

Dependency Injection (DI)

Spring 最常与其相关联的技术是反转控制的依赖项注入 (DI) 风格。反转控制 (IoC) 是一个通用概念,并且可以用许多不同的方式来表达。依赖项注入仅仅是反转控制的一个具体示例。

The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control.

在编写复杂的 Java 应用程序时,应用程序类与其它的 Java 类应该尽可能独立,以提高在单元测试时独立于其他类来重复利用和测试这些类的可能性。依赖关系注入有助于将这些类粘合在一起,并同时保持它们的独立性。

When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection helps in gluing these classes together and at the same time keeping them independent.

依赖关系注入到底是什么?让我们分别看一下这两个词。这里的依赖部分转换成了两个类之间的关联。例如,类 A 依赖于类 B。现在,让我们看一下第二部分,注入。它的全部含义是,类 B 将由 IoC 注入到类 A 中。

What is dependency injection exactly? Let’s look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent of class B. Now, let’s look at the second part, injection. All this means is, class B will get injected into class A by the IoC.

依赖关系注入可以通过向构造函数传递参数或通过使用 setter 方法而在构建后执行。由于依赖关系注入是 Spring 框架的核心,因此我们将在一个单独的章节中使用相关的示例来解释这个概念。

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will explain this concept in a separate chapter with relevant example.