http://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/
3.4 Dependencies
A typical enterprise application does not consist of a single object (or bean in the Spring parlance). Even the simplest application has a few objects that work together to present what the end-user sees as a coherent application. This next section explains how you go from defining a number of bean definitions that stand alone to a fully realized application where objects collaborate to achieve a goal.
3.4.1 Dependency Injection
Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, 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 (IoC), 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.
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 such, your classes become easier to test, in particular when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.
DI exists in two major variants, Constructor-based dependency injection and Setter-based dependency injection.
- 依赖,顾名思义就是缺了它不行。我们说一个类a依赖于类b,就是说,a如果缺少b不行,既然依赖b。那么就需要在a的里面有b类的属性,或者a类的方法中的参数类型有b类类型。一个简单的项目也不可能仅仅由一个类完成,因为类的设计是职责单一原则。所以简单的项目也是由几个不同的类一起协作完成的。
- 依赖注射,例如,a类依赖b类,那么依赖注射就是将b类注射到a类里面,注射的意思就是将b类传进去。依赖注射主要有两种方式,一种是通过构造函数进行依赖注射,一种是通过setter方法进行依赖注射