Spring Learning 2-IOC Principle control inversion/Dependency Injection

Source: Internet
Author: User
Tags ip number

Control inversion/Dependency Injection


Recently, I bought this Spring starter book: Spring in Action. The view from the hotel was good. It's a bit of a starter. Manning's book is still good, although I do not like those who only see Manning book the same focus on Manning, but with reverence for the mood and passion browse through again. Once again, the core concepts of IOC, DI, and AOP are accepted. Let's talk a little bit about IOC and DI.

IOC (DI): In fact, the concept of the core of the spring architecture is not so complex, much less obscure as some books describe. Java programmers know that every business logic in a Java program requires at least two or more objects to work together, and usually each object uses a syntax such as new object to complete the application of the partner object when using his partner object. You will find that there is a high degree of coupling between objects. The idea of the IOC is that the spring container implements the creation and coordination of these interdependent objects. Objects only need to be relational to the business logic itself. In this respect, the responsibility for how the object gets his co-object is reversed (IOC, DI).

This is my experience of spring's IOC. Di is actually another way of saying the IOC. Di 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.

If you don't understand this core concept: Here's an easy-to-understand answer from a blog called Bromon:




IOC and DI

The first thing to say is the IOC (inversion of control, controlled inversion). This is the core of spring, throughout. The so-called IOC, for the spring framework, is the responsibility of spring to control the object's life cycle and the relationship between objects. What does that 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 then spring will give you what you want when the system runs to the right time, as well as handing you over to other things that need you. 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. If you do not understand, I decided to give up.

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 to construct , 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, and spring is injected through reflection. Refer to Java Doc for information on 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.

If you don't understand, give up Java!

Let's look at how spring works.

Java code
 Public Static void Main (string[] args) {          new  filesystemxmlapplicationcontext (                  " Applicationcontext.xml ");           = (Animal) context.getbean ("Animal");          Animal.say ();      }  


You must be familiar with this code, but let's analyze it, first of all, Applicationcontext.xml.

Java code
class= "Phz.springframework.test.Cat" >          <property name= "name" value= "Kitty"/>      </ Bean>  


He has a class of phz.springframework.test.Cat

Java code
 Public class Implements Animal {      private  String name;        Public void say () {          System.out.println ("I am" + name + "!") );      }        Public void setName (String name) {          this. Name = name;      }  }   


Implements the Phz.springframework.test.Animal interface

Java code
 Public Interface Animal {      publicvoid  say ();  }  


It's obvious that the above code output I am kitty!

So how did spring do it?
Next, let's write a spring to see how Spring works!

First, we define a bean class that is used to hold a bean-owned property

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

A bean includes Id,type, and properties.

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 as follows

Java code

class= "Test" >          <property name= "TestMap" >              <map>                  <entry key= "a" >                      < value>1</value>                  </entry>                  <entry key= "B" >                      <value>2</value>                  < /entry>              </map>          </property>      </bean>  


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

Java code
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 (name, Propertiesmap); }  


The next step is to take a look at the core, and let's see how spring is dependent on injection, in fact, the idea of dependency injection is very simple, it is implemented through the reflection mechanism, when instantiating a class, it uses the Set method in the reflection call class to inject the class attribute in the HashMap into the class. Let's see how it's done.
First instantiate a class, like this

Java code
 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

Java code
 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,

Java code
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[)) Entrym Ap.getvalue ()) [0]));              }} beanprocesser.setproperty (obj, property, map); }  

OK, so we can use spring to create the class for us, is not it difficult ah? Of course, spring can do much more than that, and this sample program provides only part of spring's core dependency injection capabilities.

Reference: Spring IOC principle: http://blog.csdn.net/it_man/article/details/4402245

Spring Learning 2-IOC Principle control inversion/Dependency Injection

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.