In the Java EE platform, Spring is an excellent solution for lightweight enterprise applications. Its core technology is the IOC (inversion of Control) and AOP (aspect-oriented programming).
1. What is control inversion and dependency injection.
The IOC's English is inversion of control, which controls inversion. Developers need to create an instance of an object before using the class. But the IOC gives the task of creating the instance to the IOC container, so that the developer uses the instance of the class directly with the code, which is the IOC control reversal . Martin Fowler wrote an article to discuss the concept of inversion of control and proposed a more accurate concept called Dependency Injection (Dependency injection).
There are 3 types of dependency injection, and spring supports the latter two:
- Interface injection. Interface injection is based on separating the invocation from the implementation, which must implement the interface specified by the container, so that the program code and the container's API are bound together, not an ideal injection method.
- Setter injection. The setter method based on JavaBean assigns a value to the property. A wide range of examples are applied in practice:
Public class user{ private String name; Public String GetName () { return name; } Public void seName (String name) { this. Name = name; } }
Constructor injection. To assign a value to a property based on a construction method, the container injects its desired dependency by invoking the constructor of the class, as shown in the following example:
Public class user{ private String name; Public User (String name) { // constructor this . Name = name; // Assigning a value to a property } }
Using a construction method to assign a value to a property, the benefit is that the initialization of the property is done while instantiating the object.
What are the advantages of control inversion and dependency injection?
Because the objects are defined in the XML file in the control reversal mode, it is easier for the developer to implement a subclass and modify the XML file. Moreover, inversion of control reverses the traditional notion that "you must create before using objects," in control reversal mode, developers are no longer concerned about how a class is created, fetching a class from a container, and then invoking it directly.
The Spring core IOC