Talk about how spring IOC realizes decoupling __spring

Source: Internet
Author: User
Tags object object

Recently looking at something, suddenly think of an interview question, SPRINGIOC is how to achieve decoupling. I don't understand well.

So the first thing to think about is what is coupling.

What to do is decoupling.


We all know that in the design of software we follow a principle: Cohesion well-structured classes, low coupling

So what exactly is cohesion.

What coupling.

How to achieve high cohesion.

How to achieve low coupling.


The following is a collection of information from the Internet just to tidy up.


First: Java Cohesion well-structured classes clustering, low coupling understanding


Coupling: A measure of the degree of interconnection between different modules within a software structure (coupling is also called a link between blocks). A measure of how tightly interconnected a module is in a software system structure. The closer the link between the modules, the stronger the coupling, the worse the independence of the module, the coupling between the modules depends on the complexity of the interface between the modules, the way of invocation and the information passed. )

When coding recently, it is always hesitant to encapsulate a method in a class or to encapsulate it in a single class. It suddenly reminds me of the two nouns of cohesion coupling.

We have been pursuing, cohesion well-structured classes poly, low coupling.

For low coupling, the superficial understanding is:

A complete system, module and module, as far as possible to make its independent existence.

In other words, let each module, as far as possible, complete a specific child function.

The interface between modules and modules is as small and simple as possible.

If the relationship between the two modules is more complex, it is best to consider further module partitioning first.

This facilitates modification and combination.

For low coupling, my superficial understanding is:

Within a module, let each element be as tightly connected as possible.

That is to make full use of each element's function, each application can, in order to eventually achieve a function.

If an element is loosely related to the module, the module's structure may not be perfect, or the element is redundant.

Cohesion and coupling include horizontal and vertical relationships. Functional cohesion and data coupling are the goals we need to achieve. Transverse cohesion and coupling, usually embodied in the system of each module, the relationship between the classes, and longitudinal coupling, reflected in the system of the relationship between the various levels.

As for my confusion in coding, I think of the idea of using object-oriented thinking to consider the encapsulation of a class.
A method, how to encapsulate, to get real life, to see whether this ability (method) is the instinct of this kind of thing (class).
If it is, it is encapsulated in this class.
If not, consider encapsulation in other classes.
If this ability, many things have, it must be encapsulated in the general category of things.
If this ability, many things are often used, it can be encapsulated into a general class of static methods.

1, the degree of coupling between objects is the dependency between objects. The main problem in directing the use and maintenance of objects is the multiple dependencies between objects. The higher the coupling between objects. The higher the maintenance cost. Therefore, the object should be designed so that the coupling between the class and the widget is minimal.

2, the coupling is a measure of the correlation of each module in the program structure. It depends on the complexity of the interface between the modules, the way to call the module level of what information through the interface, the general module may be connected between the seven kinds, the coupling from low to High is: non-direct coupling, data coupling, tag coupling, control coupling , external coupling, public coupling, content coupling.

A software is assembled from multiple subroutines, and a program is composed of multiple modules (methods).
Coupling refers to the relationship tightness between individual external programs (subroutines)
and cohesion refers to the relationship between the various modules within the program close degree
So, why to high cohesion, the relationship between modules more closely, the less the error! Low coupling that is, the more complicated the relationship between subroutines, the more unexpected errors will occur! It will bring a lot of trouble to the future maintenance work.

High cohesion (high cohesion)

High cohesion is another standard commonly used to judge the quality of software design. Cohesion, a more professional term called functional cohesion, is a software system element responsibility and concentration of the measurement of relevance. If the element has a highly related responsibility, in addition to the tasks within these responsibilities, there is no more work, then the element has high cohesion, and vice versa for low cohesion. High cohesion requires that the various elements in the software system have a high degree of collaboration, because it's possible to do all sorts of things when we're doing a function in software requirements, but with a high cohesion element that only completes the task within it, and takes things that are not within its responsibility and asks others to do it. It's like, if I were a project manager, my job was to monitor and coordinate my work at all stages of my project. When my project goes into the requirements analysis phase, I ask the requirements analyst to do it, and when my project is in the development phase, I ask the software developer to do it, and when my project needs testing, I ask the tester ... If I am involved in development, I am not a high cohesive element, because development is not my responsibility. Why is our project going to be a high cohesion? I think it can be understood from four aspects of readability, reusability, maintainability and ease of change.

1. Readability

A person writes an article, speaks the matter, the clarity can be easy to understand, this also occurs in reads and writes the software code. If a pile of code written mess, East a jump West a call, read it people will feel very headache. This kind of thing may have been writing procedures for you and I have had experience. If a piece of program is very clear, each class through the name or description can clearly understand its meaning, the class of each property, function is easy to understand it should be completed tasks and behavior, this program's readability must improve. In the software industry is more and more intensive, the software industry in the collaboration of developers more and more closely, the Division of labor more and more fine today, the requirements of software readability is believed to be more and more attention.

2. Reuse of

In software development, the lowest level of reuse is a code copy, then a function of reuse, object reuse, component reuse. The laziest people in software development are the smartest people who always think of reusing. When the code is written, suddenly found that a function is once implemented function, directly copy it over OK. If this piece of code is in the same object, then it is proposed to write a function to call everywhere. If it's not in the same object, then abstract it into an object and call it everywhere. If you are not in a project, make a component for each project reference. Code reuse also makes our code more refined, robust, and code-intensive in the process of reuse. The reuse of code does bring a lot of convenience to our development, but a piece of code can be reused in all the places that need it. This gives us a new requirement for the quality of software development: Good code can be reused, and bad is not. If an object in the software can be guaranteed to fulfill the tasks within its own function, while ignoring other tasks unrelated to their functions, it can guarantee the relative independence of the function, and it can be reused in other environments from its own environment, which is an object of cohesion.

3. Maintainability and ease of change

In the previous "How to build a low coupling high cohesion software in the framework of struts+spring+hibernate," I mentioned that our current software is constantly changing, this change not only from our customers, but also from our market. If our software changes to meet our market needs in time, we can win in the market competition. How to change in time to adapt to our market, that is, by adjusting the structure of the software, so that each time we pay the minimum cost of change, the minimum cost of manpower, this change is the fastest and most economical. High cohesion software, each system, module, class task is highly relevant, so that each time the changes involved to minimize the scope. For example, the review table has changed, only with the review table objects, we will not change other objects. If we can do this, our system is, of course, a system of good maintainability and easy to change.

So, how do we get high cohesion? Take an example of the review project I mentioned earlier. I'm now going to write a section of code to fill out and save the review table for the review Table object. The responsibility of the review Table object is to update and query the data for the review table, but when displaying a review form to be filled out, I need to show the name of the review plan and the review objects that the review plan needs to review. Now how do I write a code that displays a review table to be filled in. I write a query review plan and review object code in this corresponding function of the review Table object. If you do this, your code is not high cohesion, because querying the review plan and reviewing the object's data is not its responsibility. The correct approach should be to request the review plan object and the review object object to do the work, and the review table object will simply get its results.

In addition, if an object is to complete a task that is very complex in its own area of responsibility, it should also be decomposed into several function-independent child functions. I once saw a friend write a function of hundreds of lines, which makes people read very laborious. At the same time, some of the relatively independent code in such a function can be reused in other code, and it becomes impossible. So my advice to you is not to write too long functions, more than 100 lines can be considered to decompose some of the functions out.

As with "low coupling", high cohesion is not an absolute, but a relative indicator, should be appropriate but not excessive. As we are in real life, if in a small company of ten people, each person's division of labor may be thicker, the assigned responsibilities will be a lot of miscellaneous, because the overall task is less, and if in a large company of one hundred or two hundred people, each person's division of labor will be more specialized, because the overall task is more, More need specialization division of labor to improve efficiency. Software development is the same, if the "Review plan" object to complete the business function is small, and not complex, it can fully proxy its child table "review objects" and "reviewer" management. But the basic responsibility for the "management of the review schedule" that the "review plan" object needs to complete contains a variety of business functions or complexities, it should be "management of the Review object table" to the "Review object" object, the "management of the reviewer table" to the "reviewer" object. In the same way, the high cohesion of good maintainability and easy to change can only be a relative indicator. If a change is indeed a wide range of changes, you will never be able to make a wide change through the cohesion. It also pays to get together, so you don't have to go over the design for an unlikely change, and you should have a degree. Excessive cohesion will increase the dependence of elements in the system and improve the coupling degree. Therefore, "high cohesion" and "low coupling" is contradictory, must weigh the pros and cons, comprehensively to deal with. In the UML and pattern application of Li Yang and other people's translation, cohesion and coupling are translated into yin and yang in software engineering, which is the best explanation for Chinese cohesion and coupling.

To sum up, the "high cohesion" to the software project brings advantages: Strong readability, easy maintenance and change, support low coupling, porting and reusability.

Low coupling (coupling)

The term "low coupling" is believed to be familiar to us, we are looking at Spring books, MVC data, design patterns of books, nowhere to mention "low coupling, cohesion well-structured classes poly", it has become one of the standards of software design quality. So what is the low coupling. Coupling is a measure of the connection, perception, and dependence of an element with other elements. The elements described here can be functions, objects (classes), or systems, subsystems, and modules. If an element a is to connect element B, or it can perceive B in its own way, or when B does not exist, it is said that element A is coupled with element B. The problem with coupling is that when element B changes or does not exist, it will affect the normal functioning of element A, affecting the maintainability and ease of system change. At the same time, element A can only work in an environment where element B exists, which also reduces the reusability of element A. Because of the disadvantages of coupling, we strive to pursue "low coupling" in software design. Low coupling is the requirement that in our software system, an element should not be overly dependent on other elements. Please note the word "excessive" here. Low coupling in the system can not be excessive, for example, we design a class may not be coupled with the JDK, this is possible. Unless you're not designing a Java program. Again, for example, I've designed a class that doesn't have to be coupled to any class in my system. If there is such a class, then it must be low cohesion (I'll discuss the problem of cohesion later). Coupling and cohesion are often two aspects of a contradiction. The best solution is to find a suitable middle point.

What is coupling.

1. Element b is an attribute of element a, or element a refers to an instance of element B (this includes a method called by element A, whose argument contains element B).

2. Element a invokes the method of element B.

3. Element A is a subclass of element B, either directly or indirectly.

4. Element A is the implementation of interface B.

Fortunately, there are already a number of frameworks that help us reduce the coupling of our systems. For example, using struts we can apply the MVC model, separating the page presentation from the business logic, and doing a low coupling between the page presentation and the business logic. When our pages show need to change, we just need to modify our pages without affecting our business logic; again, when our business logic needs to change, we just need to modify our Java program to be irrelevant to our page. Using spring we use the IOC (reverse control) to reduce the interdependence of the various classes in the business logic. If Class A calls Class B because of the need for function f, in the usual case class A needs to refer to Class B, so Class A relies on class B, which means that class A cannot be used when Class B does not exist. Using IOC, Class A calls only a class that implements the interface of function f, which may be Class B or another Class C, which is determined by the spring's configuration file. In this way, Class A is no longer dependent on class B, the degree of coupling is reduced and reusability is increased. Using Hibernate is the separation of our business logic from data persistence, that is, the operation of storing data in a database. We just need to put the data in the value object in the business logic, then give it to hibernate, or get the value object from Hibernate. As for Oracle, MySQL, or SQL Server, I have nothing to do with the operation.

However, as a good developer, it is not enough to rely solely on a framework-provided approach to reducing software coupling. In my experience, we should draw attention to the following questions:

1 design software according to possible changes

We use responsibility-driven design, the design of the "low coupling, cohesion well-structured classes together" a very important premise is that our software is constantly changing. If there is no change we certainly do not have to work so hard, but if there are changes, we hope that through the above design, so that we adapt or change such changes in time, to pay a smaller price. A very important message here is that we are trying to reduce the coupling in places where changes can occur because there is a cost to reducing the coupling, at the expense of increased resource consumption and code complexity. If some elements of the system are unlikely to change, or the cost of reducing the coupling is too great, we should of course choose coupling. Once I tried to keep my presentation from being tied to struts, but found it too costly to lose meaning. For the part of the software that may change, we should try to reduce the coupling, which gives us a requirement that the future changes can be prepared in the software design. Based on past experience I believe that the business logic of a software and the technical framework adopted are often 2 aspects that are easy to change. Customer requirements change is our software design must consider the problem. In the RUP development process, why the analysis design process should be divided into analysis models and design models, fools believe that the process from analysis model to design model is actually a process from satisfying direct customer demand to optimizing system structure and adapting to predictable customer requirement change. This change in customer requirements is not just a change to a customer's needs, but also the process by which our software adapts to a customer's needs to meet more customer needs. Another aspect, now that technology is changing fast, EJB, Hibernate, Spring, Ajax, a technology like merry-go from our mind, we really do not know what to use tomorrow. In this case, adapting to change is our best choice.

2 Reasonable division of responsibilities

Reasonable division of responsibilities, so that the objects of the system, not only to improve the requirements of cohesion, but also can effectively reduce coupling. such as review plan bus, review table bus, review report bus need to pass the Review plan DAO to query some of the review program data, if they are to directly call the review plan DAO (such as Figure A), then review plan bus, review table bus, review report bus three objects are coupled to the review plan DAO , the review plan DAO once changed will be related to all three objects. In this case, the review plan bus is actually the information specialist (I'll discuss the information expert model later), the Review table bus and the review report bus if you need to obtain the data of the review plan, you should submit the requirement to the review plan bus and provide the data by the Review plan bus (Figure B). After this adjustment, the coupling degree of the system is reduced.

3 using interfaces rather than inheritance

Through the analysis of coupling, it is not difficult to find that inheritance is a kind of coupling. If subclass a inherits the parent class B, either directly or indirectly, subclass A is bound to depend on the parent class B. Subclass a must be used in an environment where the parent class B is present, and the parent class B does not exist subclass a, which will affect the portability of subclass a. Any change in the parent class B, changing or removing a function name, or changing the parameters of a function will result in subclass a having to be changed or even rewritten. This change is disastrous if the subclass dozens of of the parent class B is hundreds, even through the various modules of the project. The most typical example of this is the way we now use Hibernate and spring to design DAO objects, as described in my article "How to build a low coupling high cohesion software structure under the Struts + Spring + hibernate framework."

In short, the advantages of low coupling for software projects are: Easy to change, easy to reuse

Coupling (coupling) is a measure of the degree of dependency between modules. Cohesion and coupling are closely related, modules with strong coupling to other modules usually imply weak cohesion, while strongly cohesive modules usually imply weak coupling with other modules. The module design pursues strong cohesion and weak coupling. Cohesion (cohesion) is a measure of the degree of correlation between components within a module.

Coupling (COUPLING)


Coupling (coupling) means that the input and output of two or more two or more circuit elements or electrical networks have close coordination and interaction. The phenomenon of transmitting energy from one side to the other through interaction; In a nutshell, coupling means that two entities depend on each other for a measure. Divided into the following:

Non-direct coupling: There is no direct relationship between the two modules, the connection between them is entirely through the control of the main module and the call to achieve

Data coupling: When a module accesses another module, it exchanges input and output information between each other through simple data parameters (not control parameters, public data structures, or external variables).

Tag coupling: A group of modules pass record information through the parameter table, that is, tag coupling. This record is a substructure of a data structure, not a simple variable.

Control coupling: If a module through the transmission of switches, flags, names and other control information, obviously control the choice of another module function, is the control of coupling.

External coupling: A set of modules that access the same global simple variable rather than the same global data structure, and not pass the information of the global variable through the parameter table, are called external coupling.

Public coupling: If a group of modules have access to the same public data environment, the coupling between them is called a public coupling. The public data environment can be a global structure, a shared communication area, a public coverage area of memory, and so on.

Content coupling: Content coupling occurs between two modules if the following conditions occur

(1) One module directly accesses the internal data of another module;

(2) A module does not go through the normal entrance to another module;

(3) Two modules have a part of the program code overlap (may only appear in assembly language);

(4) A module has multiple entrances.

Coupling strength, depends on the following several factors:

(1) The invocation of a module to another module;

(2) The amount of data that a module transmits to another module;

(3) How much control a module exerts on another module;

(4) The complexity of the interface between modules.

Coupling can be divided into the following types in order from strong to weak:

(1) Content coupling. Content coupling occurs when a module directly modifies or operates another module's data, or transfers it directly to another module. At this point, the modified module relies entirely on the module that modifies it.

(2) public coupling. More than two modules that collectively reference a global data item are called public couplings.

(3) control coupling. A module in the interface to pass a signal (such as switch value, flag amount, etc.) to control another module, the receiving signal module action according to the signal value adjustment, called the control coupling.

(4) Tag coupling. A complex internal data structure is passed between modules through parameters, called tag coupling. Changes in this data structure will change the relevant modules.

(5) Data coupling. The basic type of data is passed between modules through parameters, called data coupling.

(6) Non-direct coupling. When there is no information transfer between modules, they are not directly coupled.

If there must be coupling between modules, try to use data coupling, less control coupling, limit the scope of the public coupling, and resolutely avoid the use of content coupling.


Cohesion


Cohesion (cohesion) is a measure of the degree of correlation between components within a module

I. Cohesion strength

Cohesion by strength from low to high has the following types:

(1) The occasional gathering. If there is no relationship between the components of a module, it is called accidental cohesion.

(2) Logical cohesion. Several logically related functions are placed in the same module, which is called logical cohesion. For example, a module reads input from a variety of different types of peripherals. Although the logic of cohesion is more reasonable than accidental, but the logic of the module components in the function is not related, even if the local function changes sometimes affect the overall situation, so the modification of such modules is also more difficult.

(3) time to gather. If a module completes functions that must be performed at the same time (such as system initialization), but these functions are only associated with time factors, they are called time clustering.

(4) Process cohesion. If the processing elements within a module are relevant and must be performed in a particular order, they are called process cohesion.

(5) Communication cohesion. If all components of a module manipulate the same dataset or generate the same dataset, it is called a communication cohesion.

(6) Order cohesion. If each component of a module is closely related to the same function, and the output of one component is entered as another component, it is called a sequential cohesion.

(7) Functional cohesion. All components of a module are necessary for accomplishing a single function, called a function cohesion


Second: Why Spring IOC can decouple


1. In the context of the IOC theory, we all know that 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 the cooperation of 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, and many 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.
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." On the concept and use of reflection, we should all be very clear, in layman terms, according to the given class name (string mode) to dynamically generate objects. 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.


The third part: Coupling realizes spring IOC principle analysis

The end of the article for everyone to a programmer joke: [M]

First of all congratulations to keep the students found their favorite job, the incident finally dust settled, but also a new start it. Shohong chat Time also said a lot about the work of the event, the imagination of the future, but also think of a variety of difficulties. Not to mention the other is in Beijing alone housing This is enough for any one in the workforce for several years. British weather is changeable, so the British people often talk about the weather, Beijing is not a fixed house, so the friends in Beijing can talk about renting in the time of greeting;

"Hey, where did you rent the house?" ”

"I'm at the other side of the West, very cheap ..."

"Hey, I've lived there before ..."

Many of the friends who work in Beijing are the first to consider the problem of staying overnight. There is no way "basic necessities" inside the other is OK to say, but "live" this matter in Dili or a special problem. Also asked most of the friends in Beijing, their general reaction is to find the intermediary, to save money to find their own. But now a lot of people are mostly online directly to find the landlord, and then negotiate the price and then sign the contract and then is checked in. Can not help but sigh, the development of information is not the same, really feel that there is a terminal to the Internet (whether it is a computer or mobile phone) has the world.

Must have read here already some people started to swear, this is the spring IOC rationale analysis Ah! This is nonsense!!! Above the matting, the above to get to the point.

An analysis of spring IOC in life

When it came to renting the house, it came to spring that a website like 58 of the same city would be a container for spring. There are many alternative houses (beans) available on the site, what you need to do is not to rent a child before thinking about their requirements, such as to be able to bathe, can cook, winter warm summer cool, close to work place near (this is like a process of defining the interface), and then go online to search for their own house, The premise is that the landlord has automatically published the listing information to the Internet (the process of publishing the listing information is to put the beans into the container process, the process of looking for a house is similar to the one injected in spring, and as far as direct injection or JNDI injection is concerned, the rationale is the same, and the details are different. Found the house is the injection of success, can not find that only to throw an exception. The gist is: as long as the conditions are satisfied, the house can be changed at will (as long as the interface is implemented, the details of which implementation class is irrelevant)

An analysis of spring IOC based on the direction graph

&nbs

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.