Spring Framework relies injection base case of DI

DI Dependency Injection, dependency injection
is a: a, inheritance.
has a: a member variable, dependent.
example:

    class Teacher { 
     private Phone phone; //Teacher 类依赖Phone 类
     ...
     public Teacher(){	
     this.phone = new Phone();
     } 

}
This code can be found in the following questions:
(1) When I want to change Phone generating means, such as a new Phone (String name); to initialize Phone, this time I'm going to change the Teacher of the code block.
(2) If you want to test different Phone objects, a great impact on Teacher's because the initialization Phone was written dead in the constructor Teacher's;
dependency injection above will depend directly in the constructor to initialize a Hard init way the drawbacks is that the two classes is not sufficiently independent, convenient test. There is another way we Init, as follows:

public class Teacher {

Phone phone;

public Teacher (Phone phone) {
this.phone= phone;
}
}

The above code, we will phone the object passed as a parameter to the constructor. Before calling Teacher constructor external to the phone are initialized object. Like this non-initialized rely on their own initiative, and to pass through the external dependence of the way, we called dependency injection.
Now we find that the above two issues in the presence of 1 are a good solution, simply Dependency Injection has two main advantages:
(1) decoupling, the decoupling between the dependent.
(2) it has been decoupled, it is convenient to do unit testing, especially testing Mock.
Dependence : an object needs to use other objects
implantation : There are usually three kinds of ways injection, the above there is the constructor injection interface injection, injection method, for example, another object instance is provided through the setter method.

1, the target class
is created BookService interfaces and implementation classes
created BookDao of interface and implementation class
to write xml file
write test classes

BookDao of interface and implementation class
Here Insert Picture Description
Here Insert Picture Description

BookService of interface and implementation class
Here Insert Picture Description
Here Insert Picture Description
xml file
Here Insert Picture Description
test
Here Insert Picture Description
results
Here Insert Picture Description
Here Insert Picture Description

Published 27 original articles · won praise 1 · views 1229

Guess you like

Origin blog.csdn.net/qq_40484416/article/details/102480911