How to really understand IOC

  java, question

How to really understand the SpringIOC principle, and who has a deeper understanding?

First look at the situation without IOC:

//No IOC
 class Project {
 //Implement a java developer and php developer, omitting the method implementation part
 JavaDeveloper javaer = new JavaDeveloper(){...};

You can see that Project depends on javaDeveloper. If the requirements suddenly change, Java developers will be driven out of the team and php developers will have to change the Project class:

//Modify the original JavaDeveloper as follows:
 PhpDeveloper phper = new PhpDeveloper(){...};

The downside here is that once the Project becomes complicated, there will be more and more Developers, so every change will cause the project class to have to be modified. even if there are new requirements later, it is required that this developer can be changed at any time according to the requirements. what should I do?

Now look at the situation with IOC:

//First generate a Developer interface
 interface Developer(){
 class Project {
 //In the case of IOC, setter is usually used to inject this developer.
 Developer dever = null;
 setDevloper(Developer developer){
 this.dever = developer;
 //Don't worry about dever being null here.
 //IOC framework will use set method to inject developer into Project object initialization.
 //Of course, besides the setter method, it can also be injected into the constructor.
 class PhpDeveloper implements Developer(){
 class JavaDeveloper implements Developer(){

At this time, Project no longer relies on JavaDeveloper, and there is an xml outside to manage the injected content. Here is the fragment:

<!  -here you can switch to JavaDeveloper -- >

At this time, the dependency relation is mentioned to the upper layer of Project, which is Inversion of Control, and various Developer have achieved this goal through dependency injection.

By the way, apart from spring, IOC can be implemented. In fact, a simple IOC can also be implemented by writing its own code point, which is nothing more than re-injection of read configuration generation objects. Besides IOC in JAVA, other languages also have IOC solutions.