A background

In general, between the classes (or modules) of a software program, there are methods/variables that directly call each other and use that object. For example, in the basic development of the Web, the business layer invokes objects in the persistence layer and instantiates them through New, thus creating coupling between classes.

Thus, in a real business, the high level of code complexity creates the problem of over-coupling, that is, over-dependency between classes. If the coupling degree of software design is too high, when one of the classes has a bug or business requirements, the code needs to be modified, then other classes may also be affected, resulting in a large number of modifications, resulting in poor maintainability problems. The original idea of object orientation is to modify one class of code without affecting the other.

In order to reduce the coupling degree in software design, contact the dependencies in code, hence the emergence of IOC (Inversion of control) design pattern.

Definition and understanding of IOC and dependency injection

IOC, an acronym for Inversion of control.

Instead of creating objects by hard-coding “new”, you go away from the source code, and you write the class definitions and properties and methods that you design in your program into an.XML configuration file, which of course will be written in a certain format. At runtime, Java uses “reflection” to generate objects externally from class definitions in a written.xml configuration file. This isolates the source code from the generated object. So you don’t use new to generate objects like you did before.

The so-called reflection method, that is, according to the configuration file in the full class name, to obtain the object of the class.

The above is only external, generated objects, for business needs, programs can not be without dependencies. We will also write the relationships between classes in the.xml configuration file, such as the Service class referencing the Dao class object. However, it is worth noting that the container (such as Spring) will automatically inject the generated objects into the software based on the written dependencies, that is, the instantiated Dao class objects are injected into the reference under the Service class, thus creating the dependencies. Creating dependencies in this way greatly reduces the coupling of the source code. Because when you need to change something, you just change the.xml configuration file.

This is called “dependency injection”, which injects externally generated instantiated objects into references to the object in the source code, creating dependencies between programs. This is an important implementation of IOC.

That said, the IOC did the bottom line. Virtually all the work of an IOC involves creating objects, managing them (through dependency injection), integrating objects, configuring objects, and managing the life cycle of objects.