Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the IOC principle of Spring?

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you what is the IOC principle of Spring. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

1. The background of IoC theory.

As we all know, in the software system designed by object-oriented method, its underlying implementation is composed of N objects, and all objects cooperate with each other to finally realize the business logic of the system.

Figure 1: coupled objects in a software system

If we open the back cover of a mechanical watch, we will see a situation similar to the above, where each gear rotates the hour hand, minute hand and second hand clockwise, respectively, creating the correct time on the dial.

Figure 1 depicts such a gear set that has multiple independent gears that mesh with each other and work together to accomplish a task. We can see that in such a gear set, if there is something wrong with one gear, it may affect the normal operation of the whole gear set.

The meshing relationship between gears in the gear set is very similar to the coupling relationship between objects in the software system. The coupling relationship between objects is inevitable and necessary, which is the basis of collaborative work. Now, with the increasing scale of industrial applications, the dependencies between objects are becoming more and more complex, and multiple dependencies between objects often appear. Therefore, architects and designers will face greater challenges in the analysis and design of the system. If the coupling between objects is too high, it will inevitably lead to a situation that affects the whole body.

Figure 2: complex dependencies between objects

The coupling relationship will appear not only between objects, but also between modules of software system, and between software system and hardware system. How to reduce the coupling between systems, modules and objects is one of the goals that software engineering always pursues. In order to solve the problem of excessive coupling between objects, software expert Michael Mattson put forward the IOC theory, which is used to realize the "decoupling" between objects. at present, this theory has been successfully applied to practice, and many J2EE projects have adopted the IOC framework product Spring.

two。 What is inversion of Control (IoC)

IOC is an acronym for Inversion of Control, and most books are translated as "control inversion", while others are translated as "control inversion" or "control inversion".

In 1996, Michael Mattson first proposed the concept of IOC in an article on object-oriented frameworks. We have talked a lot about the basic idea of object-oriented design and programming, and we will not repeat it any more. to put it simply, it is to decompose a complex system into cooperative objects, these object classes are encapsulated, the internal implementation is transparent to the outside, thus reducing the complexity of solving problems, and can be flexibly reused and extended. The idea put forward by IOC theory is generally like this: decoupling between objects with dependencies is achieved with the help of "third parties", as shown in the following figure:

Figure 3:IOC decoupling process

As you can see, due to the introduction of the "third party" in the middle, that is, the IOC container, the four objects A, B, C and D have no coupling relationship, the transmission between gears all depends on the "third party", and the control of all objects is handed over to the "third party" IOC container. Therefore, the IOC container has become the key core of the whole system, and it plays a role similar to "adhesive". Glue all the objects in the system together to work, without this "glue", objects and objects will lose contact with each other, which is why some people compare IOC containers to "glue".

Let's do another experiment: remove the IOC container in the middle of the image above, and then take a look at the system:

Figure 4: the system after removing the IoC container

What we are seeing now is all that we need to accomplish in order to achieve the whole system. At this time, the four objects A, B, C and D are no longer coupled and not related to each other, so that when you implement A, you no longer have to think about B, C and D. the dependency between objects has been reduced to a minimum. So, if you can really implement the IOC container, it will be a wonderful thing for system development, each member involved in the development as long as the implementation of their own class, has nothing to do with others!

Let's see again, why on earth does IOC have such a name? Let's compare:

Before the IOC container is introduced into the software system, as shown in figure 1, object A depends on object B, so when object An initializes or runs to a certain point, it must take the initiative to create object B or use the created object B. Whether you create or use object B, control is in your own hands.

After the introduction of the IOC container into the software system, this situation has completely changed. As shown in figure 3, due to the addition of the IOC container, there is no direct contact between object An and object B. therefore, when object A runs to the need for object B, the IOC container will actively create an object B to inject it where object A needs it.

Through the comparison before and after, it is not difficult to see that in the process of obtaining dependent object B, object A has changed from active behavior to passive behavior, and the control has been reversed, which is the origin of the name "control inversion".

3. Alias for IOC: dependency injection (DI)

In 2004, Martin Fowler discussed the same question: since IOC is an inversion of control, then "which aspects of control have been reversed?" After detailed analysis and argumentation, he came to the answer: "the process of obtaining dependent objects has been reversed." After the control is reversed, the process of obtaining dependent objects is changed from self-management to active injection by the IOC container. So he gave "inversion of control" a more appropriate name, "dependency injection (Dependency Injection)." His answer actually gives a way to implement IOC: injection. The so-called dependency injection is that the IOC container injects some dependency into the object dynamically during the run time.

Therefore, dependency injection (DI) and control inversion (IOC) describe the same thing from different angles, that is, through the introduction of IOC container, the use of dependency injection to achieve decoupling between objects.

Let's give a life example to help understand the process of dependency injection. Everyone should be familiar with USB interface and USB equipment. USB provides great convenience for us to use computers. Now there are many external devices that support USB interface.

Figure 5:USB interface and USB device

Now, we use the host computer and the USB interface to accomplish a task: read a file from an external USB device.

When the host computer reads the file, it doesn't care what external device is connected to the USB interface, and it really doesn't need to know. Its task is to read the USB interface, and the attached external devices only need to comply with the USB interface standard. So, if I connect a USB disk to the host computer, the host will read the file from the USB disk; if I connect the host computer to an external hard drive, the host computer will read the file from the external hard drive. The power to connect external devices is up to me, that is, the control belongs to me. As for what equipment is connected to the USB interface, the host computer can not decide, it can only accept it passively. When the mainframe computer needs external equipment, I will take the initiative to help it hang up the external equipment it wants without it telling me at all. You can see how well my service is. This is a common example of dependency injection in our lives. In the process, I acted as an IOC container.

Through this example, the idea of dependency injection is very clear: when the host computer reads the file, I hook it up with the external device it depends on. The whole process of external device injection is exactly the same as when a dependent object is injected into another object while the system is running.

Let's apply dependency injection to the software system and describe the process:

Object A depends on object B, and when object A needs to use object B, the IOC container immediately creates an object B to give it to object A. IOC container is an object manufacturing factory, what you need, it will be sent to you, you can use it directly, and you no longer have to care about how the things you use are made or how they are destroyed in the end, all handled by IOC containers.

In traditional implementation, the relationship between components is controlled by the internal code of the program. We often use the new keyword to implement the combination of relationships between two components, which results in coupling between components. IOC solves this problem very well, it changes the relationship between components from the inside of the program to the external container, that is, the container dynamically injects some dependency between components into the component at run time.

4. What benefits does IOC bring to us?

Let's start with the example of USB, what are the benefits of using an USB external device over using a built-in hard drive?

First, the USB device, as the external device of the host computer, does not have any relationship with the host computer before it is plugged into the mainframe. Only after it is connected by us, the two are related. Therefore, no matter what happens to either side, it will not affect the operation of the other side. This characteristic is reflected in software engineering, that is, the maintainability is good, it is very convenient for unit testing, easy to debug programs and diagnose faults. Each Class in the code can be tested separately and does not affect each other, as long as it ensures that its own function is correct, which is the benefit of low coupling or no coupling between components.

Second, the irrelevance between USB equipment and computer mainframe also brings another benefit. Manufacturers of USB equipment and manufacturers of computer mainframe can be completely unrelated to each other, doing their own things, and the only thing they need to abide by is the USB interface standard. This feature is reflected in the software development process, but the benefits are too great. Each member of the development team only needs to care about implementing their own business logic, and there is no need to care about the progress of other people's work, because your task has nothing to do with others, and your task can be tested separately. your task does not have to rely on other people's components, and you no longer have to be responsible. Therefore, in a large and medium-sized project, team members have a clear division of labor and responsibilities, it is easy to divide a large task into small tasks, development efficiency and product quality will be greatly improved.

Third, the same USB external device can be plugged into any device that supports USB, can be plugged into the mainframe of the computer, can also be plugged into the DVD machine, and the USB external device can be used repeatedly. In software engineering, this feature is good reusability. We can separate the common components with universality and reuse them to other parts of the project, or other projects. Of course, this is also the basic feature of object-oriented. Obviously, IOC not only better implements this principle, but also improves the reusability of modules. Implementations that meet the interface standard can be plugged into modules that support this standard.

Fourth, like USB peripherals, the module has hot-swappable features. The way IOC generates objects is changed to external mode, that is, the object generation is defined in the configuration file, so that when we change an implementation subclass, it will be very easy, as long as we modify the configuration file, it is completely hot-pluggable.

Aren't the above benefits enough to impress us to use the IOC framework in the project development process?

5. Technical analysis of IOC container

The most basic technology in IOC is "Reflection" programming, which is currently supported in .net C #, Java and PHP5, among which PHP5's technical books are sometimes translated as "mapping". With regard to the concept and usage of reflection, we should all know that, in popular terms, objects are generated dynamically according to the given class name (string mode). This programming method allows the object to decide what kind of object it is when it is generated. The application of reflection is very extensive, and many mature frameworks, such as Hibernate and Spring frameworks in Java, NHibernate and Spring.Net frameworks in .Net, all take "reflection" as the most basic technical means.

Reflection technology actually appeared a long time ago, but it has been ignored and has not been further used. At that time, reflection programming was at least 10 times slower than normal object generation. Now the reflection technology has been improved and optimized, and it has become very mature. The speed of object generation by reflection is almost the same as that of the usual object generation, about 1-2 times the gap.

We can think of the working mode of the IOC container as the sublimation of the factory pattern, and we can think of the IOC container as a factory where the objects to be produced are defined in the configuration file, and then use the reflective programming of the programming language to generate the corresponding objects according to the class names given in the configuration file. From the implementation point of view, IOC is to change the object generation code previously written in the factory method to be defined by the configuration file, that is, to separate the factory and object generation, in order to improve flexibility and maintainability.

6. Some products of IOC container

The IOC containers under the Sun ONE technology system are: lightweight Spring, Guice, Pico Container, Avalon, HiveMind; heavyweight EJB;, JBoss,Jdon and so on. As one of the three musketeers of SSH (Struts, Spring, Hibernate) in Java development, Spring framework is very mature and widely used in large, medium and small projects. EJB is also used in key industrial projects, such as some telecommunications services.

The IOC containers under .net technology system are: Spring.Net, Castle and so on. Spring.Net is an IOC container migrated from Java's Spring, and Castle's IOC container is the Windsor part. They are lightweight frameworks, more mature, in which Spring.Net has been gradually used in a variety of projects.

7. What should you pay attention to when using the IOC framework

Using IOC framework products can bring great benefits to our development process, but we should also fully understand the shortcomings of introducing IOC framework, be aware of it, and put an end to abuse of the framework.

First, due to the introduction of a third-party IOC container in the software system, the steps of generating objects become somewhat complex, which is originally a matter between the two, and there is an extra procedure out of thin air, so when we first start to use the IOC framework, we will feel that the system does not become very intuitive. Therefore, the introduction of a new framework will increase the cost of training for team members to learn and understand, and in the future operation and maintenance, new entrants have to have the same knowledge system.

Second, because the IOC container generates objects through reflection, there is a certain loss in running efficiency. If you want to pursue operational efficiency, you have to weigh it.

Third, specific to the IOC framework products (such as: Spring), need to do a lot of configuration work, more tedious, for some small projects, objectively may also increase some work costs.

Fourth, the maturity of the IOC framework product itself needs to be assessed. If an immature IOC framework product is introduced, it will affect the entire project, so this is also an implicit risk.

This is what the editor shares with you about the IOC principle of Spring. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report