Spring Series's talk about the spring IOC understanding

Source: Internet
Author: User
Tags ip number java se

People who have studied the spring framework will surely hear the two concepts of Spring's IOC (inversion of Control) and DI (Dependency injection), which, for beginners of spring, always feel that the two concepts of IOC and DI are ambiguous and difficult to understand. Today, we share some of the technologies on the Web. Daniel's understanding of the spring Framework's IOC and my understanding of the spring IOC.

I. Sharing the iteye of the IOC
The first thing to share is the iteye, the technical bull's understanding of the Spring Framework's IOC is very easy to read, and the following is all from the original

1.1. What is the IOC?

  ioc-inversion of control, or "inversion of controls", is not a technique, but a design idea. in Java development,IOC means handing over your designed objects to container control rather than the traditional direct control within your object. How to understand the good IOC? The key to understanding the IOC is to make it clear "who controls who, what controls, why it is reversed (there should be a reversal in reverse), and which aspects are reversed", so let's look at it in depth:

who controls who, what controls: traditional Java SE Programming, we create objects directly within objects through new, is the program to create dependent objects, and the IOC has a special container to create these objects, that is, the IOC container to control the creation of objects; Who Controls who? The IOC container, of course, controls the object; That is the primary control of external resource acquisition (not just objects such as files, etc.).

Why reverse, what is reversed: There is a reversal of the forward, the traditional application is our own active control in the object to directly obtain the dependent object, that is, the reverse is the container to help create and inject dependent objects; because the container helps us to find and inject dependent objects, the object is only passively accepting dependent objects, so it is reversed; The acquisition of the dependent object is reversed.

 Illustrated by the legend, the traditional programming 1-1, are actively to create related objects and then combined together:

Figure 1-1 Legacy applications

When you have a Ioc/di container, you are no longer actively creating these objects in the client class, as shown in 2-2:

Figure 1-2 Ioc/di container Post-Program structure

1.2. What the IOC can do

IoC is not a technology, but an idea, an important object-oriented programming law that can guide us in designing loosely coupled, better programs. Traditional applications are created by us to create dependent objects within the class, which causes the class to be highly coupled to the class and difficult to test; with the IOC container, the control of creating and finding dependent objects is given to the container, which is injected by the container, so that the object is loosely coupled with the object, so it is also easy to test. Facilitates functional reuse and, more importantly, makes the entire architecture of the program very flexible.

In fact , the biggest change of the IOC to programming is not from the code, but from the thought, the "master-slave Transposition" change. The application was originally the boss, to get what resources are active attack, but in Ioc/di thought, the application becomes passive, passively wait for the IOC container to create and inject the resources it needs.

  IOC is a good embodiment of the object-oriented design of one of the rules of Hollywood: "Do not call us, we find you", that is, the IOC container for the object to find the corresponding dependent objects and injected, rather than the object to be actively looking for.

1.3. IOC and DI

di-dependency injection, or "dependency injection" : dependencies between components are determined by the container at run time, in the image, that is, the container dynamically injects a dependency into the component . the purpose of dependency injection is not to bring more functionality to a software system, but to increase the frequency of component reuse and to build a flexible and extensible platform for the system. through the dependency injection mechanism, we only need to use simple configuration, without any code to specify the resources required by the target, to complete its own business logic, without the need to care about where the specific resources come from and by whom.

The key to Understanding di is: "Who depends on who, why they need it, who injects it, and what is injected into it," Let's look at it in depth:

Who depends on who: of course the application relies on the IOC container ;

Why you need to rely on: applications need an IOC container to provide the external resources required by the object ;

who injects who: it is obvious that an IOC container injects an object into an application, an application-dependent object ;

What is injected: the external resources (including objects, resources, constant data) that are required to inject an object.

  What is the relationship between the IOC and di ? In fact , they are different angles of the same concept , because the concept of inversion of control is ambiguous (may be only understood as a container control object this level, it is difficult to think of who to maintain the object relationship), so the 2004 master figure Martin Fowler also gives a new name: "Dependency Injection", relative to the IOC," Dependency Injection" clearly describes the "injected object relies on the IOC container Configuration dependent objects".

Read many of the spring's IOC understanding of the article, a lot of people on the IOC and DI interpretation are obscure, anyway, is a kind of inexplicable, the sense of the unknown, after reading is still confused, the feeling is open Tao This technical ox people write particularly easy to understand, he clearly explained the IOC (control inversion) and Di ( Dependency injection) in each of the words, after reading to give people a sense of the enlightened. I believe that it is very helpful for the people of the spring framework to understand the IOC.

Second, share Bromon's blog on the IOC and Di easy to understand the explanation

2.1, IoC (inversion of control)
First you want to say IoC (inversion of control, inversion of controls) . This is Spring's core , throughout. . What does this mean, for example, how do we find a girlfriend? The common situation is that we go everywhere to see where there is a beautiful body and good mm, and then inquire about their interests, QQ number, telephone number, IP number, IQ number ..., find ways to know them, give them what they want, then hey ... The process is complex and profound, and we have to design and face each link ourselves. The same is true of traditional program development, in an object, if you want to use another object, you have to get it (your own new one, or a query from Jndi), after the use of the object will be destroyed (such as connection, etc.), the object will always and other interfaces or classes together.

So how does the IOC do it? It's kind of like finding a girlfriend through a dating agency, introducing a third party between me and my girlfriend: the Marriage Institute. Matchmaking management of a lot of men and women's information, I can give a list of matchmaking, tell it I want to find a girlfriend, such as like Michelle Reis, figure like Lin Xire, singing like Jay Chou, speed like Carlos, technology like Zidane, and then the matchmaking will be according to our requirements, provide a mm, We just have to go to love her and get married. As simple as it is, if a matchmaking person doesn't meet our requirements, we'll throw an exception. The whole process is no longer controlled by myself, but by a similar container-like institution that has a matchmaking system. This is how spring advocates for development , and all classes are registered in the spring container, telling spring what you are, what you need, and spring will give you what you want when the system runs to the proper time, It also gives you the other things you need. All classes are created and destroyed by spring, which means that the object that controls the lifetime of the object is no longer a reference to it, but spring. For a specific object, it was previously controlled by other objects, and now all objects are controlled by spring, so this is called control inversion.

2.2, DI (Dependency injection)

 A key point of the IOC is to dynamically provide the other objects it needs to an object during the system's operation. This is achieved through DI (Dependency injection, Dependency injection) . For example, object A needs to manipulate the database, before we always have to write code in a to get a connection object, with spring we just need to tell spring,a need a connection, as for this connection how to construct , when constructed, a does not need to know. When the system is running, Spring creates a connection at the right time, and then, like an injection, it injects into a, which completes the control of the relationship between the various objects. A relies on connection to function properly, and this connection is injected into a by spring, and the name of the dependency injection comes in. So how is di implemented? An important feature after Java 1.3 is reflection (reflection), which allows the program to dynamically generate objects, execute methods of objects, and change the properties of objects when it is run, andspring is injected through reflection .

With the understanding of the IOC and Di concepts, everything becomes straightforward and the rest of the work is just piling up wood in the spring frame.

Iii. My understanding of IOC (inversion of Control) and Di (Dependency injection)

In the normal Java application development, we want to implement a certain function or to complete a business logic at least two or more objects to collaborate to complete, when not using spring, each object in need to use his partner object, they have to use like new object () Such a syntax to create a cooperative object, this cooperation object is created by their own initiative, the initiative to create a cooperative object in their own hands, which partners need to work on their own initiative to create, the initiative to create cooperation objects and the creation of the timing is self-control, and this will make the coupling between the object is high, A object needs to use partner B to do one thing together, a to use B, then A has a dependency on B, which is a coupling between A and B, and is tightly coupled, and the use of spring is not the same, the work of creating partner B is done by spring, Spring creates a B object and stores it in a container, and when the A object needs to use a B object, spring takes the B object that is in the container that holds the object, and then gives it to the A object, as to how spring creates that object, and when to create the object's , a object does not need to care about these details (when you were born, how it was born I do not care, can help me to work on the line), a get spring to our object, two people together to complete the work to complete.

So the control reversal IOC (inversion of control) is to say that the creation of the object is transferred, the initiative and creation time of the previously created object is controlled by itself, and now this power is transferred to the third party , such as transferred to the IOC container, It is a factory dedicated to creating objects, you want what object, it gives you what object, with the IOC container, the dependency is changed, the original dependency is gone, they all rely on the IOC container, through the IOC container to establish their relationship.

This is my understanding of Spring's IOC(inversion of control) . Di(Dependency injection) is actually another argument of the IOC, which was first proposed by Martin Fowler in a paper in early 2004. He concludes: What control is reversed? is: the way to get dependent objects is reversed.

Iv. implementation principles of IOC

The focus of the IOC is to dynamically provide other objects that it needs to an object during the system's operation. This method is provided through Di (dependency injection). For example, a class needs a Class B object to complete an action, formerly a class of their own new A B, with spring, just tell Spring,a need a B, as for b how to construct, when to construct, a completely do not need care, just need to open the mouth when it needs to be done. When the system is running, Spring creates a b at the appropriate time and then injects it into a as an injection, thus completing the association control between the objects. A depends on B to run normally, and the B object is injected by spring into a. This is how dependency injection comes in.

Implementation of Di

Di is implemented by reflection, which allows the program to get the class itself by the name or object of a class. Spring is through reflection to complete the injection.

Next, manually write a threaded version of the spring IOC container.
First, we define a bean class, which is used to hold properties owned by a bean.

    /**/    private  String    ID; /*  */    private  String type    ; /*  *    /privatenew hashmap<string, object> ();

A bean consists of the Id,type (class-wide domain name), and the properties (domain).

Then spring starts loading our configuration file, storing the information we have configured in a HashMap, HashMap's key is the Bean Id, Hasmap's value is the bean, Only in this way can we get the animal class through Context.getbean ("Animal"). We all know that spirng can inject basic types, and can inject types like list,map, so let's take a map example to see how spring is stored.

The map configuration can be like the following.

<BeanID= "Test"class= "Test">        < Propertyname= "TestMap">            <Map>                <entryKey= "a">                    <value>1</value>                </entry>                <entryKey= "B">                    <value>2</value>                </entry>            </Map>        </ Property>    </Bean>

How does spring Save the above configuration? The code is as follows:

if(Beanproperty.element ("map")! =NULL) {Map<string, object> propertiesmap =NewHashmap<string, object>(); Element Propertieslistmap=(Element) beanproperty. Elements (). Get (0); Iterator<?> Propertiesiterator =Propertieslistmap. Elements (). iterator ();  while(Propertiesiterator.hasnext ()) {Element vet=(Element) propertiesiterator.next (); if(Vet.getname (). Equals ("entry") ) {String key= Vet.attributevalue ("Key"); Iterator<?> Valuesiterator =vet.elements (). iterator ();  while(Valuesiterator.hasnext ()) {Element value=(Element) valuesiterator.next (); if(Value.getname (). Equals ("Value") {propertiesmap.put (key, Value.gettext ()); }                                if(Value.getname (). Equals ("ref") {propertiesmap.put (key,Newstring[] {value. AttributeValue ("Bean") }); }}}} bean.getproperties (). Put (n                Ame, Propertiesmap); }

The next step is to get to the core, and let's see how spring is dependent on injection , but the idea of dependency injection is simple, and it's implemented through a reflection mechanism, and when you instantiate a class, It injects class attributes previously saved in HashMap into the class by reflecting the set method in the call class. let's see how it's done.
First instantiate a class, like this

 Public StaticObject newinstance (String className) {Class<?> CLS =NULL; Object obj=NULL; Try{CLS=Class.forName (className); Obj=cls.newinstance (); } Catch(ClassNotFoundException e) {Throw NewRuntimeException (e); } Catch(instantiationexception e) {Throw NewRuntimeException (e); } Catch(illegalaccessexception e) {Throw NewRuntimeException (e); }        returnobj; }

Then it injects the dependency of this class, like this

 Public Static voidsetProperty (Object obj, string name, String value) {Class<?extendsObject> Clazz =Obj.getclass (); Try{String MethodName=returnsetmthodname (name); Method[] Ms=Clazz.getmethods ();  for(Method m:ms) {if(M.getname (). Equals (MethodName)) {if(M.getparametertypes (). length = = 1) {Class<?> Clazzparametertype = m.getparametertypes () [0];                        SetFieldValue (Clazzparametertype.getname (), value, M, obj);  Break; }                }            }        } Catch(SecurityException e) {Throw NewRuntimeException (e); } Catch(IllegalArgumentException e) {Throw NewRuntimeException (e); } Catch(illegalaccessexception e) {Throw NewRuntimeException (e); } Catch(InvocationTargetException e) {Throw NewRuntimeException (e); }}

Finally it returns an instance of this class to us and we can use it. Let's take map as an example to see how it's done, and the code I write is to create a hashmap and inject the HashMap into the class that needs to be injected, like this

if(ValueinstanceofMap) {Iterator<?> Entryiterator = ((map<?,? >) value). EntrySet (). iterator (); Map<string, object> map =NewHashmap<string, object>();  while(Entryiterator.hasnext ()) {Entry<?,? > Entrymap = (entry<?,? >) Entryiterator.next (); if(Entrymap.getvalue ()instanceofstring[]) {map.put (String) Entrymap.getkey (), Getbean (((string[)) ENTRYMAP.G Etvalue ()) [0]));            }} beanprocesser.setproperty (obj, property, map); }

So we can use spring to create classes for us (although the details are not very clear, some of the methods do not know what the actual implementation is)
Of course, spring can do much more than that, and this sample program provides only part of spring's core dependency injection capabilities.

Spring Series's talk about the spring IOC understanding

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.