B: Inversion of Control.
Look at an example from life:
The advantage here is obvious, that is, the project team does not need to pay attention to recruitment, interview, salary and so on a bunch of things, just need to put forward the requirements of employment can be.
Corresponding to code:
The nice thing here is that Class A doesn’t have to worry about how the Class to use is created. You just have to declare that you want to use the Class, and the container will create and inject the Class.
How the container allocates Class B to Class A leads to dependency injection (DI).
3. Dependency Injection
There are several ways A container can inject Class B into Class A:
1. Constructor injection:
Class A
private B b;
@Autowired
public A(B b) {
this.b = b; }}Copy the code
2. Parameter injection
Class A
@Autowired
public void exec(B b) { b.doSomeThing(); }}Copy the code
3. Attribute injection
Class A
@Autowired
private B b;
public void exec(a) { b.doSomeThing(); }}Copy the code
Benefits of dependency injection
The essential benefit is decoupling, whereas Spring’s dependency injection benefits are:
1. Easy to test, dependent objects are injected, so you can Mock an object during unit tests and inject it to test and compare the following code:
Class A {
public void exec(a) {
B b = new B();
b.doSomeThing();
}
}
Class A {
public void exec(B b) { b.doSomeThing(); }}Copy the code
The first method, Class B, is built in-house and cannot be Mock tested, while the second method can be passed in Mock Class B.
2. There is no need to implement the singleton pattern by itself. Beans in Spring are singleton pattern by default.
3. Dependency injection (DI) enables the container to manage beans and their life cycle in a unified manner. When managing the life cycle of beans, some common common logic can be implemented in a unified manner without the need for each Bean to be implemented separately.
end.
Spring Boot introduction (2) Knowledge map Spring Boot introduction (4) global exception handling
Site: javashizhan.com/
Wechat Official Account: