Understanding of Spring Inversion of Control and Dependency Injection - Vivid Image (IOC, DI)

1. IOC Inversion of Control

IOC : inversion of control - a process of instantiation.
The initiative of instantiation is handed over to Spring in the form of configuration, and the instantiated object is placed in the Spring container. That is,
the object of the Java class is managed through the Spring container, rather than a new object in the Java class.

Hollywood law: "Don't come to us, we will come to you"
Why is it called inversion of control? As the name implies, transfer control of finding (instantiating) the object to the container, rather than controlling the object itself.

Did not understand? Don't worry! look down.
Let me tell you in advance:
don't look for us , don't introduce another class into your own class stupidly, the coupling degree is high, and it will affect the whole body~
We are looking for you , you are not looking for me, how to use us, only ourselves It's time to come. This door-to-door visit is not about laying the foundation and building a house at your place, but that we bring our family with our household registration and real estate certificate. That is to say, we have everything we need, and we are the target. We don’t need new, just inject it for you to use . .

2. DI dependency injection

DI: Dependency Injection
purpose: maintain loose coupling

2.1 Conventional method

In order to show his adventurous spirit, the knight created a new Quest object, and then operated on this object. The knight defeated the villain Bully, he felt that he had upgraded, "I am the best in the world", I am going to kill the dragon. However, the knight found out, where the hell am I going to find the dragon? Well, I have worked so hard to find the dragon class under the premise of forcing the programmer to introduce it manually. Only an external dragon class can kill the dragon, which is so troublesome.

junior knight

// 骑士类
public class Knight {
    
    
	private Quest quest;
	public Knight() {
    
    
		this.quest = new Quest();
	}
	
	public void embark() {
    
    
		System.out.println("骑士将要做的事:");
		quest.killBully();
		
	}
}

Adventure 1 - Badass

//冒险类1---坏蛋类
public class Quest1 {
    
    
	public String killBully() {
    
     //打败坏蛋
		return "kill Bully";
	}
}

upgraded knight

Well, as a knight I can now slay dragons. Thanks to the new code farmer who helped me introduce the dragon class! Coder, do you have such a question: directly add a method to the Quest1-bad guy class, let the bad guy ride a dragon, and I, as a knight, just introduce a dragon-slaying method. Coders think again, no, doesn't this destroy the encapsulation of Java? Combining two entity classes into one, do you want to fight the BOSS directly, no! What if there are blue dragons and white dragons in the world?

// 骑士类
public class Knight {
    
    
	private Quest1 quest1;
	private Quest2 quest2;
	public Knight() {
    
    
		this.quest1 = new Quest1();
		this.quest2 = new Quest2();
	}
	
	public void embark() {
    
    
		System.out.println("骑士将要做的事:");
		quest1.killBully();
		quest2.killDragon();
	}
}

Adventure 2--Dragon

//冒险类2
public class Quest2 {
    
    
	public String killDragon() {
    
     //屠龙
		return "kill dragon";
	}
}

2.2 The bald knight

The knight felt that he could not save face by always relying on programmers to do things for him. So, one day, the knight found an intermediary, that is, the Spring container, and the intermediary can inject a series of information into the knight through the form of XML configuration. Now the code farmer is in a hurry, are you not going to hang up? Code farmers want to learn this technology, and then get the knight's business back!
Then I will teach you "injection" ! !
First instill a vocabulary in you: interface

Upgraded Expedition

public interface QuestPro {
    
    
	public void embark();
}

bad guy explored

public class BullyImpl implements QuestPro {
    
    

	@Override
	public void embark() {
    
    
		System.out.println("kill bully");
	}

}

dragon explored

public class DragonImpl implements QuestPro {
    
    

	@Override
	public void embark() {
    
    
		System.out.println("kill dragon");
	}

}

strongest knight

public class KnightPro {
    
    
	private QuestPro questPro;
	public KnightPro(QuestPro questPro) {
    
    //QuestPro被注入进来
		this.questPro = questPro;
	}
	
	public void quest() {
    
    
		questPro.embark();
	}
}

Said the knight!

Adding an interface is injection ? Not! Coder, think about it, if QuestPro has been injected into the knight class, then who will instantiate this QuestPro?
The answer is intermediary! Inject an object into the knight through XML configuration, without requiring the knight to create a new one.
Knight: It’s true that I can’t new by myself. Even if the interface is implemented, when I make new by myself, I still need to new two objects!

QuestPro q1 = new BullyImpl();
QuestPro q2 = new DragonImpl();

What's the difference between this and no interface! Still have to rely on intermediary injection. Directly inject the object, I will use whatever you inject, and all comers are welcome.

public KnightPro(QuestPro questPro) {
    
    //QuestPro被注入进来
		this.questPro = questPro;
	}

3. Summary

Coders get it! If the knight wants to continue to upgrade, whether it is a monster or an Ultraman, as long as the QuestPro interface is implemented; the intermediary injects an object into the knight, then the knight can make a move, and there is no need to change the inside.
It is too troublesome to take risks with long guns and short cannons, and it is the strongest to travel lightly!

The whole idea of ​​the program is inversion of control, and the specific implementation uses dependency injection!
The technical term means:
Inversion of control: the initiative of instantiation is handed over to Spring, which is carried out in the form of configuration, and the instantiated object is placed in the Spring container.
Dependency Injection:
What is a dependency? The adventure class depends on the knight class, and there is no adventure without a knight!
What is injection? That is, you don't need to instantiate objects yourself, and the objects used are all passed in from the outside world.

4. Summary

dependency injection

The following text comes from the rookie tutorial

There are two core functions of the Spring framework:

  1. As a super factory, the Spring container is responsible for creating and managing all Java objects, which are called Beans.
  2. The Spring container manages the dependencies between Beans in the container, and Spring uses a method called "dependency injection" to manage the dependencies between Beans.

Using dependency injection, you can not only inject ordinary property values ​​into beans, but also inject references to other beans. Dependency injection is an excellent way of decoupling, which allows beans to be organized together in configuration files rather than coupled together in a hard-coded way.
Understanding Dependency Injection

Rod Johnson was the first person who attached great importance to managing the collaboration relationship of Java instances with configuration files. He gave this method a name: Inversion of Control (Inverse of Control, IoC). Later, Martine Fowler gave this method another name: Dependency Injection (Dependency Injection), so whether it is dependency injection or inversion of control, its meaning is exactly the same . When a Java object (caller) needs to call a method of another Java object (dependent object), there are usually two approaches in the traditional mode:

原始做法: 调用者主动创建被依赖对象,然后再调用被依赖对象的方法。
简单工厂模式: 调用者先找到被依赖对象的工厂,然后主动通过工厂去获取被依赖对象,最后再调用被依赖对象的方法。

Pay attention to the word "active " above , which will inevitably lead to hard-coded coupling between the caller and the dependent object implementation class, which is very unfavorable for the maintenance of project upgrades. After using the Spring framework, the caller does not need to actively obtain the dependent object. The caller only needs to passively accept the Spring container to assign values ​​to the caller's member variables. It can be seen that after using Spring, the way the caller obtains the dependent object is changed from the original Active acquisition becomes passive acceptance-so Rod Johnson calls it inversion of control.

In addition, from the perspective of the Spring container, the Spring container is responsible for assigning the dependent object to the member variable of the caller-equivalent to injecting the instance it depends on for the caller, so Martine Fowler calls it dependency injection.

The technique most recognized by Spring is the Dependency Injection (DI) pattern of Inversion of Control. Inversion of Control (loC) is a general concept that can be expressed in many different ways, dependency injection is just one specific example of Inversion of Control. W3Cschool's explanation

5. Summarize again

The rookie tutorial above said that dependency injection and inversion of control are exactly the same. I think the two are just different in focus.
The inversion of control focuses on adding instances to the Spring container, that is, adding Beans, configuring XML,

Guess you like

Origin blog.csdn.net/qq_43709785/article/details/119953970