[Java] Spring Ioc explanation, not afraid you don't understand
Quote: IoC (Control inversion: Inverse of Control) is the kernel of the Spring container. The functions such as AOP and declarative transactions blossom on this basis. However, the concept of IoC is rather obscure and difficult to understand. This is a big pity. However, IoC does include many meanings. It involves considerations about code decoupling, design patterns, and code optimization. We plan to use a small example to illustrate this concept.
Understanding the concept of IoC through instances
The New Year's blockbuster has already formed a tradition in China. At the end of every year, many new year's blockbuster movies will be overwhelmed. Among all the New Year's blockbusters, Zhang zhiliang's moattacking is a brilliant one. The film tells the story of the heroic man who helped Liang Guo resist Zhao's aggression in the Warring States period. The magnificent and dignified historical scenes of hunxiong are rather shocking. One of the scenarios is that when the mojie.com played by Andy Lau leaves the city of liangguo, Liang guoshoujun asked: "Who are the visitors ?" Liu Dehua replied: "mo zhige !" We may wish to write a script for this "city gate inquiry" scenario using a Java class and understand the concept of IoC:
Code List 3-1 MoAttack: arrange scripts by actors
Java code
- Public class MoAttack {
- Public void cityGateAsk (){
- // ① Actors intrude directly into the script
- LiuDeHua ldh = new LiuDeHua ();
- Ldh. responseAsk (!);
- }
- }
We will find that the above script is located at ①, and Andy Lau, who acts as an operator of the specific role, directly intrude into the script, so that the script and the actors are directly coupled (Figure 3-1 ).
A wise scriptwriter should focus on the role of the story when creating the story, instead of the specific actors of the role, so that he can freely select any suitable actors during the script shooting, not bound to Andy Lau. Through the above analysis, we know that an interface needs to be defined for the hero of the script:
Code List 3-2 MoAttack: Introduce the script role
Java code
- Public class MoAttack {
- Public void cityGateAsk ()
- {
- // ① Introduce the exit role Interface
- GeLi geli = new LiuDeHua ();
-
- // ② Implement the plot through the interface
- Geli. responseAsk (!);
- }
- }
In section ①, the role of the script is introduced. The plot of the script is expanded by the role. The role is played by the actors during shooting, as shown in section ②. As a result, the class graph relationships of Moti, Geli, and Andy Lau are shown in Figure 3 2:
However, from Figure 3 2, we can see that MoAttack depends on the GeLi interface and LiuDeHua class at the same time, and does not achieve the goal of relying only on roles as we expected. However, the role must be shot only by a specific actor. How can LiuDeHua be independent of the script and complete the specific GeLi action? Of course, when the film is shot, the Director arranges LiuDeHua on the role of GeLi. The director assembles the script, role, and operator (Figure 3-3 ).
By introducing directors, the script is decoupled from the specific actors. Corresponding to the software, the Director acts as an assembler and arranges actors to perform specific roles.
Now we can explain the concept of IoC in turn. The literal meaning of IoC (Inverse of Control) is Control inversion, which includes two contents:
- One is control
- Second, reverse
So what is the "control" being "Reversed? As shown in the preceding example, "control" refers to the control right of the player who chooses the GeLi role. "reversal" refers to the removal of this control right from the mo attacking script and transfer it to the director. For software, that is, the right to select a specific implementation class of an interface is removed from the calling class and transferred to a third party for decision.
Because IoC is not open enough, it has been widely discussed in the industry. Finally, Martin Fowler, a Thai character in the software field, proposed the concept of DI (Dependency Injection: Dependency Injection) to replace IoC, that is, the call class's dependency on an interface implementation class is injected by a third party (container or collaboration class) to remove the call class's dependency on an interface implementation class. The term "dependency injection" is obviously clearer and easier to understand than "control reversal.
IoC type
The injection method can be divided into three types: constructor injection, property injection, and interface injection. Spring supports constructor injection and property injection. The following example shows the differences between the three injection methods.
Constructor Injection
In constructor injection, we call the constructor of the class to pass in the interface implementation class through the constructor variable, as shown in Figure 3-3 of the Code:
Code List 3-3 MoAttack: inject the attacker through the constructor
Java code
- Public class MoAttack {
- Private GeLi geli;
- // ① The operator of the injection Leather
- Public MoAttack (GeLi geli ){
- This. geli = geli;
- }
- Public void cityGateAsk (){
- Geli. responseAsk (!);
- }
- }
The MoAttack constructor does not care who plays the role, as long as the operator passed in at ① completes the corresponding performance as required by the script. The specific roles are arranged by the Director, as shown in the code list 3-4:
Code List 3-4 ctor: inject the attacker through the constructor
Java code
- Public class Director {
- Public void direct (){
- // ① Specify the role player
- GeLi geli = new LiuDeHua ();
-
- // ② Inject the specific actors into the script
- MoAttack moAttack = new MoAttack (geli );
- MoAttack. cityGateAsk ();
- }
- }
At ①, the director arranged for Liu Dehua to play the role of Ge Li, and at ②, he "injected" Liu Dehua into the mo attacking script, and then began the performance of the story "the city gate inquiry.
Property Injection
Sometimes, the Director may find that, although leather is the primary character of the film "ink attack", not all scenes need to be replaced, in this case, constructor injection is equivalent to the presence of an operator who is always on the fly. It is not visible properly. In this case, attribute injection can be considered. Property injection can selectively use the Setter method to inject the dependencies required for calling classes, making it more flexible and convenient:
Code List 3-5 MoAttack: inject the attacker using the Setter Method
Java code
- Public class MoAttack {
- Private GeLi geli;
- // ① Property Injection Method
- Public void setGeli (GeLi geli ){
- This. geli = geli;
- }
- Public void cityGateAsk (){
- Geli. responseAsk ();
- }
- }
MoAttack provides a Setter method for the geli attribute at ①, so that the director can inject the specific actors of geli as needed.
Code List 3-6 ctor: inject the attacker using the Setter Method
Java code
- Public class Director {
- Public void direct (){
- GeLi geli = new LiuDeHua ();
- MoAttack moAttack = new MoAttack ();
-
- // ① Call the Setter Method for property Injection
- MoAttack. setGeli (geli );
- MoAttack. cityGateAsk ();
- }
- }
Unlike the operator injection through the constructor, when the MoAttack script is instantiated, no operator is specified. Instead, the setGeli () operator is called only when the MoAttack script is instantiated () method injection operator. In a similar way, we can also provide the Setter injection method for other roles in the script, such as Liang Wang and Xiang Yan. In this way, the director can follow the different stages of the drama, the corresponding role is injected.
Interface Injection
Extract all the dependent injection methods of the call class to an interface. The call class provides corresponding injection methods by implementing this interface. To adopt the interface injection method, you must declare an ActorArrangable interface first:
Java code
- Public interface ActorArrangable {
- Void injectGeli (GeLi geli );
- }
Then, MoAttack implements the ActorArrangable interface to provide specific implementation:
Code List 3-7 MoAttack: inject the attacker using the Interface Method
Java code
- Public class MoAttack implements ActorArrangable {
- Private GeLi geli;
- // ① Interface Implementation Method
- Public void injectGeli (GeLi geli ){
- This. geli = geli;
- }
- Public void cityGateAsk (){
- Geli. responseAsk ();
- }
- }
Director uses the injectGeli () method of ActorArrangable to inject actors.
Code List 3-8 Director: interface-based injection
Java code
- Public class Director {
- Public void direct (){
- GeLi geli = new LiuDeHua ();
- MoAttack moAttack = new MoAttack ();
- MoAttack. injectGeli (geli );
- MoAttack. cityGateAsk ();
- }
- }
Because an additional interface needs to be declared through interface injection, the number of classes is increased, and its effect is not essentially different from that of attribute injection, we do not advocate this method.
Inject dependency through containers
Although MoAttack and LiuDeHua implement decoupling, MoAttack does not need to pay attention to the instantiation of the Role Implementation class, but these work still exists in the Code and is only transferred to the Director class. Assume that a producer wants to change this situation. After selecting a script, the producer wants to select directors and actors through a "Hai Xuan" or a third intermediary organization to perform their respective duties, the scripts, directors, and actors are all decoupled.
The so-called Media "Hai Xuan" and third-party intermediary organizations are a third-party container in the field of procedures. It helps to complete class initialization and assembly, developers can get rid of the underlying implementation class instantiation and dependency assembly, and focus on more meaningful business logic development. This is undoubtedly a desirable thing. Spring is such a container that describes the dependency between classes through configuration files or annotations, class initialization and dependency injection are automatically completed. The following is a piece of configuration file for configuring the above instances in the Spring configuration file:
Xml Code
- Xmlns: xsi = http://www.w3.org/2001/XMLSchema-instance
- Xmlns: p = http://www.springframework.org/schema/p
- Xsi: schemaLocation = http://www.springframework.org/schema/beans
- Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd>
- P: geli-ref = geli/>
Use new XmlBeanFactory ("beans. xml") to start the container. When the container starts, Spring automatically instantiates the Bean based on the description in the configuration file and completes dependency assembly. The ready Bean instance can be returned from the container, which can be directly used in the future.
Why does Spring have this "magic" power? simply by using a simple configuration file, it can magically instantiate and assemble the Bean used by the program? This "magic" is attributed to the class Reflection Feature of the Java language itself.