Control inversion (IoC) vs. Dependency Injection (DI)

Source: Internet
Author: User

Objective

Recently learning the spring framework, its core is the IOC container. To master the Spring framework, it is necessary to understand the idea of inversion of control and the way that dependency injection is implemented. Below, we will explore the relationship between control inversion and dependency injection, and how to apply it in spring around the following questions.

    • What is control reversal?
    • What is dependency injection?
    • What is the relationship between them?
    • How do I apply dependency injection in the spring framework?
What is control reversal

Before we discuss control inversion, let's look at the coupling objects in the software system.
Figure 1: Coupling objects in a software system
As you can see, the objects in the software work together like gears, but with each other, a part doesn't work and the whole system crashes. This is a strongly coupled system. The meshing relationship between gears in a gear group is very similar to the coupling relationship between the objects in the software system. The coupling between objects is unavoidable and necessary, which is the basis of collaborative work. Now, with the increasing scale of industrial applications and the increasingly complex dependencies between objects, there are often multiple dependencies between objects, so architects and designers will face greater challenges in analyzing and designing systems. It is inevitable that the reaching will occur when the coupling between the objects has passed the high system.

To solve the problem of high coupling between objects, software expert Michael Mattson proposed the IOC theory to achieve "decoupling" between objects.

control inversion (inversion of controls) is a design principle in object-oriented programming, which is used to reduce the degree of coupling between computer code. The basic idea is to use "third party" to realize the decoupling between the objects with dependencies.
Figure 2:IOC Decoupling process
Due to the introduction of the intermediate position of the "third party", that is, the IOC container, so that a, B, C, D these 4 objects do not have a coupling relationship, the transmission between the gears all rely on "third party", all the control of the object to the "third party" IOC container, so, the IOC container becomes the key core It acts like an "adhesive" that binds all objects in the system together, and if there is no "binder", the objects and objects will lose touch with each other, which is the origin of the IOC container being likened to an "adhesive".
Let's take a look at why the inversion of Control (IOC) is a name? Let's compare:

    1. Before the introduction of the IOC container, the software system 1 shows that object a relies on object B, so when object a initializes or runs to a certain point, it must take the initiative to create object B or Use object B that has already been created. Whether you are creating or using object B, you have control over your own hands.
    2. After the introduction of the IOC container, the software system completely changed, 2, as the IOC container joins, object A and object B lose direct contact, so when object a runs to object B, the IOC container will actively create an object B to inject to object a where it is needed.

Through the contrast, we do not look ugly: object A to rely on the process of object B, from the active behavior to passive behavior, control reversed, this is the name of "control reversal" the origin.

Control inversion is not just a theory of software engineering, we also use it in our lives. Give another example of real life:
Haier Company as an electrical manufacturers need to distribute their goods to all parts of the country, but found that different distribution channels have different gameplay, so sent a variety of sales representatives play different gameplay, with more and more channels, found that each additional channel will add a number of people and a new process, Heavily coupled and dependent on the gameplay of each channel trader. Really can not stand, so the establishment of business standards, the development of distribution information systems, only in line with this standard channel to become Haier's distributors. Let the various channel vendors in turn rely on their own standards. Invert the control and invert the dependency.

We regard Haier and distributors as software objects, distribution information system as an IOC container, it can be found that before the IOC container, the distributor is like the gears in Figure 1, adding a gear to increase the number of dependencies on other gears, will inevitably lead to more complex system. After developing the distribution system, all distributors rely only on the distribution system, as shown in Figure 2, it is convenient to add and remove gears up.

What is Dependency injection

Dependency Injection is the passing of an instance variable into an object (Dependency injection means giving a object its instance variables).

What is dependency

If there is an instance of Class B in Class A, it is said that Class A has a dependency on class B. For example, the following class Human uses a Father object, and we say that class Human has a dependency on the class Father.

 Public class Human {    ...    Father Father;    ...      Public Human () {        new  Father ();    }}

Looking closely at this code, we will find that there are some problems:

    1. If you want to change the Father generation mode now, if you need to initialize the father with new father (String name), you need to modify the Human code;
    2. It is difficult to test the effect of different Father objects on Human because the initialization of Father is written dead in the Human constructor;
    3. If the new Father () process is very slow, it is also difficult for us to Mock off the process with an already initialized Father object.
Dependency Injection

The above dependency on direct initialization in the constructor is a hard init method, with the disadvantage that two classes are not independent enough to be tested easily. We also have another Init method, as follows:

 Public class Human {    ...    Father Father;    ...      Public Human (Father Father) {        this. Father = Father;    }} 

In the above code, we pass in the Father object as a parameter to the constructor. The Father object has been initialized externally before calling Human's constructor method. Like this kind of non-self-initiated dependency, and through the external to pass through the dependency, we are called dependency injection.
Now we find that the two problems in 1 above are well solved, and simply say that dependency injection has two benefits:

    1. Decoupling, decoupling the dependencies.
    2. It is easy to do unit tests, especially Mock tests, because they are decoupled.
Control reversal and Dependency injection relationships

We have explained the concepts of control inversion and dependency injection separately. Some people equate control inversion with dependency injection, but in fact they are fundamentally different.

    • inversion of control is a kind of thought
    • Dependency Injection is a design pattern

The IOC framework uses dependency injection as a way to implement control inversion, but there are other ways to implement control inversion, such as servicelocator, so you cannot equate control inversion with dependency injection.

Dependency Injection in Spring

As we mentioned above, dependency injection is a way to achieve control inversion. Let's briefly describe this process in conjunction with the Spring IOC container.

 class   Movielister ...  private      Moviefinder finder;  public  void   Setfinder (Moviefinder finder) { this . Finder = finder;  class   Colonmoviefinder ...  public  void   Setfilename (String filename) {  filename; }

We define two classes and see that we use dependency injection in a way that relies on external incoming dependencies instead of creating dependencies on our own. So the question comes, who takes the dependency to them, that is, who is responsible for creating it and passing it on finder finder MovieLister . The answer is spring's IOC container.

To use an IOC container, you first configure it. Here we use the configuration of XML, or can be configured by code annotations. Below is spring.xml the content

<beans>    class= "Spring." Movielister ">        <property name=" finder ">            <ref local=" Moviefinder "/>        </property>    </bean>    class= "Spring." Colonmoviefinder ">        <property name=" filename ">            <value>movies1.txt</value>        </property>    </bean></beans>

In spring, each bean represents an instance of an object, which by default is a singleton pattern, that is, all objects have only one instance for reuse during the lifetime of the program. By configuring the BEAN,IOC container, the bean instance is generated according to the configuration when it is started. The specific configuration syntax references the spring documentation. As long as you know that the IOC container will be created according to the configuration MovieFinder , at run time to MovieFinder assign MovieLister the finder property to complete the dependency injection process.

The test code is given below

 Public void throws Exception {    new filesystemxmlapplicationcontext ("Spring.xml");   1    Movielister lister = (movielister) ctx.getbean ("Movielister");   2    movie[] movies = Lister.moviesdirectedby ("Sergio Leone");    Assertequals ("Once upon a time in the West", Movies[0].gettitle ());}
    1. Generated according to ApplicationContext the configuration, that is, the IOC container.
    2. Gets the instance from the container MovieLister .
Summarize
    1. Control inversion is an idea of decoupling in software engineering, and invoking a class relies only on interfaces, not on specific implementation classes, and reduces coupling. Control is given to the container, which is then determined by the container to "inject" the concrete implementation into the object of the calling class.
    2. Dependency Injection is a design pattern that can be used as a way to implement control inversion. Dependency injection is the passing of an instance variable into an object (Dependency injection means giving a object its instance variables).
    3. Through the IOC framework, the strong coupling relationship of Class A relies on class B can be established at run time through a container, that is, the work of creating a B instance is handed over to the container, and class A can use it.

Reference articles
Ioc/dip is actually a kind of management thought
Inversion of Control Containers and the Dependency injection pattern
Dependency Injection
Learn from Me Spring 3 (4) – In-depth understanding of IOC (control inversion) and Di (Dependency injection)

Control inversion (IoC) vs. Dependency Injection (DI)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.