Spring Technology Insider: SPRINGIOC Principle Learning Summary

Source: Internet
Author: User

Some time ago I saw the Spring Technology insider's chapter on the IOC principle, feel the code too much, not good grasp, I deliberately collected some information on the IOC principles, especially to deepen the impression, in order to really master the principles of the IOC.
The IOC idea 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.
The steps to perform the SPRINGIOC container are:
1. Resource positioning, which is to find the Applicationcontext.xml file first
2. Loading of Beandefinition, the data in the XML file is loaded uniformly into the beandefinition, which is convenient for later processing.
3. Inject beandefinition data into the IOC container
4, the data in the Beandefinition to the 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 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.
As a real-life example, there are many intermediary companies, such as I love my home. I love my family will have a variety of property information, when we find a house we just need to tell me the house needs to love my home, I love my family will be based on our needs to provide us with a suitable house. So we do not have to go online, community advertising and other places to collect the search for their own house, the whole process by I love my home intermediary to control on the line, now think of this intermediary is not to make the whole process become simple and enjoyable. Of course, in real life in the face of intermediaries we need to pay intermediary fees, like SPRINGIOC we also need to maintain applicationcontext this configuration file, are costs, in the face of spring we can ignore the cost, haha.
Let me take a look at SPRINGIOC's running process:
1, first load applicationcontext.xml, resource positioning
First, the resource location is finally in the Abstractbeandefinitionreader class under Springframe.LoaderBeanDefinitions(String location,Set<Resource> actualResources)Line 98, the following examples:

publicstaticvoidmain(String[] args) {        new FileSystemXmlApplicationContext(                "applicationContext.xml");        User user= (User) context.getBean("user");        user.write();    }
 <bean id  = "user"  class  = " Com.jader.spring.Model.User " > <property  name  =" name " value=" Jader "/> </ Bean>  
publicclass User{    private String name;    publicvoidwrite() {        System.out.println("my name is:"+name);    }    publicvoidsetName(String name) {        this.name = name;    }}

The running program outputs: My name is Jader, and it is clear that SPRINGIOC has injected the value of the property into the user's name attribute.
Let's analyze how spring is implemented.
2. Loading of Beandefinition
Loading and parsing is finally implemented by the refresh () method of the Abstractapplicationcontext class under Springframework, which is very critical, including resource loading and parsing, which includes additional processing of lazy-init, etc. Line 445, the following examples:
First we define a bean to hold the bean-owned properties

 /* Bean Id */ private  string  ID;    /* Bean class */ private  string     type ;    /* Bean Property */ private  map  <  string , Object>  properties =  new  hashmap<  string , Object>  ();  

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 by Context.getbean ("user"). 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.

   <bean id="Beanmap" class="Beanmap">        < property name="Mybeanmap">            <map>                <entry key="name">                    <value>Jader</value>                </Entry>                <entry key="Age">                    <value>26</value>                </Entry>            </map>        </Property >    </Bean>

3. Registering with the IOC container beandefinition
The registration is finally registerbeandefinition under the Defaultlistablebeanfactory class of spring frame (String beanname,beandefinition Beandefinition) method, line 664, for example:

if (beanproperty. Element("Map") = null) {map<string, object> propertiesmap = new hashmap<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, new string[] {value. AttributeValue("Bean") });}}}} Bean. GetProperties(). Put(Name, Propertiesmap);}

4. Dependency Injection
The ultimate dependency Injection of SPRINGIOC is through Abstractautowirecapablebeanfactory's Docreatebean (Finale String beanname,final Rootbeandefinition mbd,final object[] args) method (line 480), the key methods in this method are Populatebean () and createbeaninstance (), Implementing injection is implemented by the setPropertyValue () method of the Beanwrapperimpl extends Abstractpropertyaccessor class line 911
The principle is that, by reflection, when a class is instantiated, it injects class attributes that were previously saved in HashMap into the class by reflecting the set method in the Call class

 Public StaticObjectnewinstance(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 }
 Public Static void SetProperty(Object obj, string name, stringvalue{class<? extends object> 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.

          if(ValueinstanceofMAP) {iterator<?> Entryiterator = ((map<?,? >) value). EntrySet (). Itera                Tor (); map<String,Object> map =Newhashmap<String,Object> (); while(Entryiterator.hasnext ()) {entry<?,? > entrymap = (entry<?,? >) entryiterator.next ();if(Entrymap.getvalue ()instanceof String[]) {Map.put (String) Entrymap.getkey (), Getbean ((String[]) Entrymap.getvalue ()) [0]));            }} beanprocesser.setproperty (obj, property, map); }

Each step of the specific implementation I have labeled the class name, method name and number of lines, you can view the spring source code, not shown here.
In the face of spring technology inside the first chapter of the introduction of SPRINGIOC principle, difficult to understand, with the help of this article can be helpful for us to understand. Read times, its righteousness from the present, when you do not understand the time you can read repeatedly, this article I have collected from the online multi-party information, here I express my thanks, I hope we progress together.

Spring Technology Insider: SPRINGIOC Principle Learning Summary

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.