1.4.1. Dependency Injection(依赖注入)
Dependency injection (DI) is a process whereby objects define their dependencies (that is, the other objects with which they work) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes or the Service Locator pattern.
依赖注入(DI)是一个过程。在这过程中,对象仅通过构造函数参数、工厂方法的参数、或(在构造对象实例后,或从工厂方法返回后,在对象实例上设置的)属性来定义其依赖项(即与之一起工作的其他对象)。然后,容器在创建bean时注入这些依赖项。这个过程基本上是bean本身的逆过程(因此称为控制反转(Inversion of Control)),通过使用直接构造类(direct construction of class)或服务定位器(Service Locator)模式来控制其依赖项的实例化或定位。
Code is cleaner with the DI principle, and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies. As a result, your classes become easier to test, particularly when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.
使用DI原则,代码更干净,当对象具有依赖关系时,解耦更有效。对象不查找其依赖项,也不知道依赖项的位置或类(location or class)。因此,您的类变得更容易测试,特别是当依赖项位于接口或抽象基类上时,这允许在单元测试中使用存根或模拟(stub or mock)实现。
DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.
DI有两种主要变体:基于构造函数的依赖注入Constructor-based dependency injection 和基于Setter的依赖注入(Setter-based dependency injection)。