Spring's IOC principles [popular explanation]

Source: Internet
Author: User
Tags reflection

1. Background of the IOC theory
As we all know, in the software system designed by object-oriented method, its bottom implementation is composed of N objects, and all objects realize the business logic of the system through cooperating with each other.

Figure 1: Coupling objects in a software system

If we turn on the back cover of a mechanical watch, we will see a similar situation where each gear rotates clockwise, minute and second seconds to produce the correct time on the dial. This is described in Figure 1, which has a plurality of independent gears that are meshed together to work together to accomplish a task. We can see that in such a gear group, if there is a problem with a gear, it may affect the entire gear group's normal operation.
The meshing relationship between gears in the gear group is very similar to the coupling relationship between the objects in the software system. The coupling relationship between objects is unavoidable and necessary, which is the basis of collaborative work. Now, with the growing scale of industrial applications and the increasing complexity of dependencies among objects, there are often multiple dependencies between objects, so architects and designers will face greater challenges to the analysis and design of systems. When the coupling between objects is passed through a high system, the far-reaching situation will inevitably occur.

Figure 2: Complex dependencies between objects

The coupling relationship not only occurs between objects and objects, but also between the modules of software systems and between software systems and hardware systems. How to reduce the coupling between the system, between the modules and the objects is one of the goals that software engineering always pursues. to solve the problem of coupling between objects , software expert Michael Mattson The IOC theory to achieve "decoupling" between objects, a theory that has been successfully applied to practice, Many of the Java EE projects have adopted the IOC framework product spring.

2. What is control reversal (IoC)
The IOC is the abbreviation for control of inversion, and most books are translated as "controlled inversion", and some books are translated as "control reverse" or "control inverted".
In 1996, Michael Mattson The concept of the IOC in an article on the discussion of object-oriented frameworks. For the basic idea of object-oriented design and programming, we've already talked a lot about it, and it's simple to break up complex systems into mutually cooperative objects that, after encapsulation, are transparent to the outside, reducing the complexity of problem solving and being flexible to reuse and extend. The point of view of the IOC theory is generally this: by using "third party" to implement the decoupling between objects with dependencies, the following figure:

Figure 3:IOC Decoupling process

You see, because of the introduction of the middle position of the "third party", that is, the IOC container, so that a, B, C, D these 4 objects without a coupling relationship, gear transmission between all rely on "third party", all the control of the object turned over to the "third party" IOC container, so, The IOC container becomes the key core of the whole system, it acts like a "binder" that ties together all the objects in the system, and if there is no "binder", the object and object will lose contact with each other, which is how the IOC container is likened to the origin of "binder".
Let's do another experiment: take off the IOC container in the middle of the picture, and then look at the system:

Figure 4: System after taking off the IOC container

The picture we're looking at now is all we need to do to implement the entire system. At this time, a, B, C, D these 4 objects have no coupling relationship between each other, so that when you implement a, there is no need to consider the B, C and D, the dependencies between the objects have been reduced to the lowest degree. So, if the IOC container could really be implemented, it would be a wonderful thing for system development, and each member involved in the development would be able to implement its own class and have no relationship with anyone else.
Let's take a look at why the control reversal (IOC) has such a name. Let's make a comparison:
Before the IOC container is introduced into the software system, as shown in Figure 1, object A relies on object B, so object A must take the initiative to create object B or Use object B that has been created when initializing or running to a certain point. Whether you are creating or using object B, control is in your own hands.
After the introduction of the IOC container, the software system this situation is completely changed, as shown in Figure 3, as the IOC container joins, object a loses direct contact with object B, so when object a runs to object B, the IOC container takes the initiative to create an object B to inject into the place that object a needs.
Through the contrast, we do not look ugly: object A to obtain the process of relying on object B, from the active behavior into passive behavior, control reversed, this is the "control reversal" The origin of the name.

3. IOC Alias: Dependency Injection (DI)
Martin Fowler the same question in 2004, and since the IOC is a reversal of control, what is the "control that has been reversed"? After detailed analysis and argument, he came to the answer: "The process of acquiring dependent objects has been reversed". After the control is reversed, the process of acquiring the dependent object is changed from its own management to active injection by the IOC container. So he took a more appropriate name for "control reversal" called "Dependency Injection (Dependency injection)". His answer, in fact, gives a way to achieve the IOC: injection. The so-called dependency injection is that the IOC container dynamically injects a dependency into the object during its operation.

Therefore, Dependency injection (DI) and control inversion (IOC) are the same thing that is described from different angles, that is, by introducing the IOC container and using dependency injection to achieve decoupling between objects .
We give an example of life to help understand the process of dependency injection. Everyone on the USB interface and USB devices should be very familiar with it, USB for us to use the computer to provide a lot of convenience, now have a lot of external devices are supported USB interface.

Figure 5:usb Interface and USB devices

Now we are using a computer host and USB interface to accomplish a task: reading a file from an external USB device.
When a computer host reads a file, it does not care about what external devices are connected to the USB interface, and it does not need to know. Its task is to read the USB interface, attached to the external devices as long as the USB interface standards can be met. So, if I connect a USB disk to a computer host, then the host reads the file from the U disk, and if I connect an external hard drive to the computer host, the computer host reads the file from the external hard drive. The power of hanging external equipment by my lord, that is, control right to me, as for the USB interface is what equipment, computer host is not decided, it can only passively accept. The computer host needs the external equipment, does not need it to tell me at all, I will take the initiative to help it to hang the external equipment which it wants, you see my service is how in place. This is a common example of dependency injection in our lives. In the process, I played the role of the IOC container .
In this example, the idea of dependency injection is already very clear: when a computer host reads a file, I put the external device it relies on to hook him up. The process of injecting an entire external device is exactly the same as when a dependent object is injected into another object while the system is running.
We apply dependency injection to a software system, and then describe the process:
Object A relies on object B, and when object a needs to use object B, the IOC container immediately creates an object B to object A. The IOC container is an object manufacturing plant, you need something, it will be sent to you, you can use it directly, and no longer need to care about how the things you use are made, and do not care how the last is destroyed, all of which are arranged by the IOC container.
In the traditional implementation, the internal code of the program controls the relationship between components. We often use the New keyword to implement a combination of relationships between the two components, and this implementation can result in coupling between components. The IOC solves the problem well by referring to the external container within the program, which means that the container dynamically injects a dependency between components into the component at runtime.

4. What benefits does the IOC bring us

Let's just say from the USB example, what's the benefit of using a USB external device than using a built-in hard drive.
First, the USB device as a computer host of external devices, before inserting the host, and the computer host has no relationship, only by our connection, the two only after the contact, has relevance. So no matter what happens to either side, it doesn't affect the other side's operation. This characteristic manifests in the software engineering, is the maintainability is better, is very easy to carry on the unit test, facilitates the debugging procedure and the diagnosis fault. Each class in the code can be tested individually, without affecting each other, as long as it is guaranteed to function correctly, which is the benefit of low coupling or decoupling between components.
Second, the USB device and computer host between the Independent, but also brings another benefit, the production of USB equipment manufacturers and manufacturers of computer mainframe can be completely unrelated to each other, the only thing they need to observe is the USB interface standard. This feature is reflected in the software development process, the benefits are too big. Members of each development team only need to be concerned with implementing their own business logic, there is no need to care about other people's work progress, because your task has nothing to do with others, your task can be tested alone, your task does not depend on other people's components, no longer have to be confused about responsibility. Therefore, in a large and medium-sized projects, team members clear division of labor, responsibility is clear, it is easy to a large task divided into small tasks, development efficiency and product quality will be greatly improved.
Third, the same USB external device can be plugged into any USB device, can plug into the computer host, can also plug into DV machine, USB peripherals can be reused. In software engineering, this feature is good for reusability, we can separate commonly used components, and reuse to other parts of the project, or other projects, of course, this is the basic object-oriented characteristics. Obviously, IOC not only implements this principle better, but also improves the reusability of modules. Implementations that conform to the interface standards can be plugged into modules that support this standard.
Four, as with USB peripherals, the module has hot-swappable characteristics. The way in which the IOC generates objects is to go externally, that is, to define the object generation in a configuration file, so that when we replace the implementation subclass it will be very simple, as long as the configuration file is modified so that there is a full hot-swappable feature.
The above benefits are not enough to impress us, let us use the IOC framework in the project development process.

5. Technical analysis of the IOC container
The most basic technology in the IOC is "reflection (Reflection)" programming, which is currently supported in languages such as. Net C #, Java, and PHP5, where PHP5 's technical books are sometimes translated as "mappings."As for the concept and usage of reflection, we should all be very clear, in layman terms, to dynamically generate objects based on the given class name (string method)。 This method of programming allows an object to decide which object it is to build. The application of reflection is very extensive, many mature frameworks, such as Hibernate in Java, Spring Framework. NET in NHibernate, spring.net frame is to "reflect" as the most basic technical means.
Reflection technology has been in fact very early, but has been neglected, has not been further exploited. The reflection programming at that time was at least 10 times times slower than the normal method of generating objects. Now the reflective technology has been improved and optimized, it has been very mature, the reflection way to generate objects and the usual object generation methods, the speed is not large, about 1-2 times the gap.
we can think of the working mode of the IOC container as the sublimation of the factory model, the IOC container can be regarded as a factory, the objects to be produced in this factory are defined in the configuration file, and then the object is generated according to the class name given in the configuration file using the programming language's reflection programming. From the perspective of implementation, the IOC is to create the code that was written dead in the factory method, and changed it to be defined by the configuration file, which is to separate the factory from the object generation, in order to improve flexibility and maintainability.
6. Some products of the IOC container
The IOC containers under the Sun One technology system are: lightweight spring, Guice, Pico Container, Avalon, Hivemind, heavyweight ejb, no light weight jboss,jdon, etc. As one of the Three Musketeers of SSH (Struts, Spring, Hibernate) in Java development, the Spring framework is very mature and widely used, and EJB is also used in critical industrial projects, such as some telecommunications services.
. Net technology system under the IOC containers are: Spring.net, Castle and so on. Spring.net is an IOC container transplanted from Java Spring, Castle's IOC container is the Windsor part. They are lightweight frameworks that are more mature, where spring.net has been gradually applied to a variety of projects.
7. What should be paid attention to using the IOC framework
The use of the IOC framework products can bring great benefits to our development process, but we should also fully understand the shortcomings of the introduction of the IOC framework, to be aware of, and eliminate abuse of the framework.
First, in the software system because of the introduction of Third-party IOC containers, the process of generating objects has become a bit more complex, it is a matter between the two, and out of thin air, so we just started using the IOC framework, we will feel the system becomes less intuitive. Therefore, the introduction of a new framework, will increase the team members to learn and understand the training costs, and in the future operation and maintenance, but also to the new participants have the same knowledge system.
Second, because the IOC container generation object is through the reflection way, in the operational efficiency has certain loss. If you're going to run for efficiency, you have to weigh it.
Third, specific to the IOC framework products (such as: Spring), the need for a large number of compounding work, more cumbersome, for some small projects, objectively may also increase some of the cost of work.
Iv. the maturity of the IOC framework product itself needs to be evaluated, and if an immature IOC framework product is introduced, it can affect the entire project, so it is also a hidden risk.
We can generally conclude that some projects or products with little work are not suitable for using the IOC framework products. In addition, if the team members of the lack of knowledge, for the IOC framework products are not in-depth understanding, nor rashly introduced. Finally, special emphasis on operational efficiency of the project or product, nor is it appropriate to introduce the IOC framework products, such as the WEB2.0 Web site is the case.

Resources:

http://jiwenke.iteye.com/blog/493965

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.