Parsing and registration of "Spring Source analysis"--bean

Source: Internet
Author: User
Tags aliases

Then the previous section continues the analysis, Defaultbeandefinitiondocumentreader's Parsebeandefinitions method:

protected void parsebeandefinitions(Element root, beandefinitionparserdelegateDelegate) {if(Delegate. Isdefaultnamespace (Root) {NodeList nl = root.getchildnodes (); for(inti =0; I < nl.getlength (); i++) {Node node = Nl.item (i);if(Node instanceof Element) {element ele = (element) node;if(Delegate. Isdefaultnamespace (Ele)) {parsedefaultelement (Ele,Delegate); }Else{Delegate. Parsecustomelement (Ele); }                }            }        }Else{Delegate. parsecustomelement (Root); }    }

The above code is a traversal of the root node of the child node code, that is, the Loop processing node, processing method is parsedefaultelement, into the Parsedefaultelement method, we found that according to the different node names, there are different processing methods, We care about the processing of bean nodes and naturally enter the Processbeandefinition method.

protected void processbeandefinition(Element ele, beandefinitionparserdelegateDelegate) {//beandefinitionholder encapsulates the name and alias of the Beandefinition, Bean, and uses it to complete the registration to the IOC container.Beandefinitionholder Bdholder =Delegate. Parsebeandefinitionelement (Ele);if(Bdholder! =NULL) {Bdholder =Delegate. decoratebeandefinitionifrequired (Ele, Bdholder);Try{//Register the final decorated instance.             //This is a beandefinition to the IOC container registration resolutionBeandefinitionreaderutils.registerbeandefinition (Bdholder, Getreadercontext (). GetRegistry ()); }Catch(Beandefinitionstoreexception ex) {getreadercontext (). Error ("Failed to register bean definition with name '"+ bdholder.getbeanname () +"'", Ele, ex); }//Send registration event.Getreadercontext (). firecomponentregistered (NewBeancomponentdefinition (Bdholder)); }    }

Well, we find that the real processing logic is in the Parsebeandefinitionelement method of the Beandefinitionparserdelegate class.

 PublicBeandefinitionholderparsebeandefinitionelement(Element ele, beandefinition Containingbean)        {String id = ele.getattribute (id_attribute);        String nameattr = Ele.getattribute (Name_attribute); list<string> aliases =NewArraylist<string> ();if(Stringutils.haslength (nameattr))            {string[] Namearr = Stringutils.tokenizetostringarray (nameattr, multi_value_attribute_delimiters);        Aliases.addall (Arrays.aslist (Namearr)); } String beanname = ID;if(! Stringutils.hastext (beanname) &&!aliases.isempty ()) {beanname = Aliases.remove (0);if(Logger.isdebugenabled ()) {Logger.debug ("No XML ' id ' specified-using '"+ Beanname +"' As Bean name and"+ aliases +"as aliases"); }        }if(Containingbean = =NULL) {checknameuniqueness (beanname, aliases, ele); }//This method will parse the bean element in detailAbstractbeandefinition beandefinition = parsebeandefinitionelement (Ele, Beanname, Containingbean);if(Beandefinition! =NULL) {if(! Stringutils.hastext (Beanname)) {Try{if(Containingbean! =NULL) {beanname = Beandefinitionreaderutils.generatebeanname (beandefin Ition, This. Readercontext.getregistry (),true); }Else{Beanname = This. Readercontext.generatebeanname (Beandefinition);//Register an alias for the plain Bean class name, if still possible,                        //If the generator returned the class name plus a suffix.                        //This was expected for Spring 1.2/2.0 backwards compatibility.String beanclassname = Beandefinition.getbeanclassname ();if(Beanclassname! =NULL&& Beanname.startswith (beanclassname) && beanname.length () > Beanclassna Me.length () &&! This. Readercontext.getregistry (). Isbeannameinuse (Beanclassname)) {Aliases.add (beanclassname); }                    }if(Logger.isdebugenabled ()) {Logger.debug ("Neither XML ' id ' nor ' name ' specified-"+"Using generated bean name ["+ Beanname +"]"); }                }Catch(Exception ex) {Error (Ex.getmessage (), ele);return NULL; }} string[] Aliasesarray = Stringutils.tostringarray (aliases);return NewBeandefinitionholder (Beandefinition, Beanname, Aliasesarray); }return NULL; }

Let's look at a more detailed analysis, another overloaded method of Parsebeandefinitionelement

 PublicAbstractbeandefinitionparsebeandefinitionelement(Element ele, String beanname, Beandefinition Containingbean) { This. Parsestate.push (NewBeanentry (Beanname));//This only resolves the class name and does not instantiateString ClassName =NULL;if(Ele.hasattribute (Class_attribute))        {className = Ele.getattribute (Class_attribute). Trim (); }Try{String parent =NULL;if(Ele.hasattribute (Parent_attribute))            {parent = Ele.getattribute (Parent_attribute); }//The Beandefinition object is established hereabstractbeandefinition bd = Createbeandefinition (className, parent);//attribute parsing of the current bean elementParsebeandefinitionattributes (Ele, Beanname, Containingbean, BD);            Bd.setdescription (Domutils.getchildelementvaluebytagname (Ele, description_element));            Parsemetaelements (Ele, BD);            Parselookupoverridesubelements (Ele, Bd.getmethodoverrides ());            Parsereplacedmethodsubelements (Ele, Bd.getmethodoverrides ());            Parseconstructorargelements (Ele, BD);            Parsepropertyelements (Ele, BD);            Parsequalifierelements (Ele, BD); Bd.setresource ( This. Readercontext.getresource ()); Bd.setsource (Extractsource (ele));returnBd }Catch(ClassNotFoundException ex) {Error ("Bean class ["+ ClassName +"] not found", Ele, ex); }Catch(Noclassdeffounderror Err) {Error ("class that Bean class ["+ ClassName +"] depends on not found", ele, err); }Catch(Throwable ex) {Error ("Unexpected failure during bean definition parsing", Ele, ex); }finally{ This. Parsestate.pop (); }return NULL; }

The above is a concrete way to generate beandefinition objects, and after so many steps, we have finally converted a bean element defined in XML into a spring-defined Beandefinition object. The next step is to register the beandefinition into the IOC container.
In fact, the IOC container is a hashmap to hold these beandefinition, the HASHMAP definition can be found in the Defaultlistablebeanfactory class:

/** Map of bean definition objects, keyed by bean name */    privatefinalnew ConcurrentHashMap<String, BeanDefinition>(64);

The specific registration method is in the Registerbeandefinition method of the Defaultlistablebeanfactory class:

 Public void registerbeandefinition(String beanname, beandefinition beandefinition)throwsbeandefinitionstoreexception {assert.hastext (Beanname,"Bean name must not be empty"); Assert.notnull (Beandefinition,"Beandefinition must not being null");if(beandefinitioninstanceofAbstractbeandefinition) {Try{((abstractbeandefinition) beandefinition). Validate (); }Catch(Beandefinitionvalidationexception ex) {Throw NewBeandefinitionstoreexception (Beandefinition.getresourcedescription (), Beanname,"Validation of bean definition failed", ex); }} beandefinition oldbeandefinition;//Ensure data consistency during registration        synchronized( This. Beandefinitionmap) {//Check here to see if a bean with the same name has been registered, and if it is registered and does not allow overwriting, throws an exceptionOldbeandefinition = This. Beandefinitionmap.get (Beanname);if(Oldbeandefinition! =NULL) {if(! This. allowbeandefinitionoverriding) {Throw NewBeandefinitionstoreexception (Beandefinition.getresourcedescription (), Beanname,"Cannot register bean definition ["+ Beandefinition +"] for Bean '"+ Beanname +"': there is already ["+ Oldbeandefinition +"] bound."); }Else if(Oldbeandefinition.getrole () < Beandefinition.getrole ()) {//e.g. was role_application, now overriding with Role_support or role_infrastructure                    if( This. logger.iswarnenabled ()) { This. Logger.warn ("overriding user-defined bean definition for bean "+ Beanname +"with a framework-generated bean definition ': replacing ["+ Oldbeandefinition +"] with ["+ Beandefinition +"]"); }                }Else{if( This. logger.isinfoenabled ()) { This. Logger.info ("overriding bean definition for bean "+ Beanname +"': replacing ["+ Oldbeandefinition +"] with ["+ Beandefinition +"]"); }                }            }//The following is the normal registration, the bean as the Key,beandefinition object as value, put into the HashMap            Else{ This. Beandefinitionnames.add (Beanname); This. Frozenbeandefinitionnames =NULL; } This. Beandefinitionmap.put (Beanname, beandefinition); }if(Oldbeandefinition! =NULL||        Containssingleton (Beanname)) {resetbeandefinition (beanname); }    }

This completes the registration of the bean, the initialization of the IOC container is complete, the container is ready to use, and the next step is to make a dependency injection, so please look forward to the next section!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Parsing and registration of "Spring Source analysis"--bean

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.