Spring parses the entire process of XML load bean

Source: Internet
Author: User
Tags aliases assert
The first step starts with the Spring container refresh
Org.springframework.context.support.abstractapplicationcontext#refresh
    Configurablelistablebeanfactory Beanfactory = Obtainfreshbeanfactory ();
        Org.springframework.context.support.abstractapplicationcontext#obtainfreshbeanfactory
        Org.springframework.context.support.abstractrefreshableapplicationcontext#refreshbeanfactory
            Loadbeandefinitions (beanfactory);
    Create a new xmlbeandefinitionreader for the given beanfactory.
        Xmlbeandefinitionreader Beandefinitionreader = new Xmlbeandefinitionreader (beanfactory);
        Beandefinitionreader.setenvironment (This.getenvironment ());
        Beandefinitionreader.setresourceloader (this);
        Beandefinitionreader.setentityresolver (New Resourceentityresolver (this));
        Initbeandefinitionreader (Beandefinitionreader);
Continue loading Bean loadbeandefinitions (beandefinitionreader); Org.springframework.web.context.support.xmlwebapplicationcontext#loadbeandefinitions ( Org.springframework.beans.factory.xml.XmlBeanDefinitionReader) protected void loadbeandefinitions (
        Xmlbeandefinitionreader reader) throws IOException {string[] configlocations = Getconfiglocations ();
            if (configlocations! = null) {//Continue loading reader.loadbeandefinitions (configlocation); }}}//Location incoming XML file address public int LoadbeaNdefinitions (String location) throws Beandefinitionstoreexception {return loadbeandefinitions (location, null); }
parsing xml and registering beans
Org.springframework.beans.factory.xml.xmlbeandefinitionreader#registerbeandefinitions Public

    int Registerbeandefinitions (Document doc, Resource Resource) throws Beandefinitionstoreexception {
        Beandefinitiondocumentreader Documentreader = Createbeandefinitiondocumentreader ();
        Documentreader.setenvironment (This.getenvironment ());
        Gets how many bean
        int countbefore = GetRegistry () exist in the current container. Getbeandefinitioncount ();
        Parsing XML registers the bean with the container
        documentreader.registerbeandefinitions (Doc, Createreadercontext (Resource));
        Returns the number of Bean return GetRegistry () registered in the container
        . Getbeandefinitioncount ()-Countbefore;
    }
org.springframework.beans.factory.xml.defaultbeandefinitiondocumentreader# Registerbeandefinitions public void Registerbeandefinitions (Document doc, Xmlreadercontext readercontext) {T

        His.readercontext = Readercontext;
        Logger.debug ("Loading bean Definitions");

        Element root = Doc.getdocumentelement ();
    Doregisterbeandefinitions (root); }
Org.springframework.beans.factory.xml.defaultbeandefinitiondocumentreader#doregisterbeandefinitions protected
        void Doregisterbeandefinitions (Element root) {String Profilespec = Root.getattribute (Profile_attribute);  if (Stringutils.hastext (Profilespec)) {assert.state (this.environment! = NULL, "Environment property must not
            be null "); string[] Specifiedprofiles = Stringutils.tokenizetostringarray (Profilespec, beandefinitionparserdelegate.multi_
            Value_attribute_delimiters);
            if (!this.environment.acceptsprofiles (specifiedprofiles)) {return; }}//any nested <beans> elements'll cause recursion in this method. In//order to propagate and preserve <beans> default-* attributes correctly,//keep track of the C Urrent (parent) delegate, which May is null. Create//The new (child) delegate with a reference to the parent for fallback purposes,//Then ultimately the reset this.delegate back to its original (parent) reference.
        This behavior emulates a stack of delegates without actually necessitating one.
        Beandefinitionparserdelegate parent = this.delegate;

        This.delegate = Createhelper (Readercontext, root, parent);
        Preprocessxml (root);
        Parse and register parsebeandefinitions (root, this.delegate);

        Postprocessxml (root);
    This.delegate = parent; } delegate the following class to process XML data information org.springframework.beans.factory.xml.BeanDefinitionParserDelegate
Org.springframework.beans.factory.xml.defaultbeandefinitiondocumentreader#parsebeandefinitions

    Protected void Parsebeandefinitions (Element root, beandefinitionparserdelegate delegate) {
        if (delegate.isdefaultnamespace (root)) {
            NodeList nl = root.getchildnodes ();
            for (int i = 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);
        }
    }
a
Org.springframework.beans.factory.xml.beandefinitionparserdelegate#isdefaultnamespace (Org.w3c.dom.Node) public
    Boolean Isdefaultnamespace (node node) {return Isdefaultnamespace (Getnamespaceuri (node)); } public boolean isdefaultnamespace (String NamespaceURI) {return (! Stringutils.haslength (NamespaceURI) | |
    Beans_namespace_uri.equals (NamespaceURI)); } org.springframework.beans.factory.xml.beandefinitionparserdelegate#nodenameequals public Boolean nodeNameEquals ( Node node, String desiredname) {return desiredname.equals (Node.getnodename ()) | | | desiredname.equals (GETLOCALNAME (
    node)); } org.springframework.beans.factory.xml.defaultbeandefinitiondocumentreader#parsedefaultelement// This location is dedicated to handling the bean registration of the private void Parsedefaultelement (Element ele, beandefinitionparserdelegate delegate) {//node is IMP
        ORT registration Processing if (Delegate.nodenameequals (Ele, import_element)) {Importbeandefinitionresource (ele); }//SectionThe dot is ALIAS's registration processing else if (Delegate.nodenameequals (Ele, alias_element)) {processaliasregistration (ele); }//node is the BEAN's registration process else if (delegate.nodenameequals (Ele, bean_element)) {Processbeandefi
        Nition (Ele, delegate);
            }//node is BEANS's registration process else if (delegate.nodenameequals (Ele, nested_beans_element)) {//Recurse
        Doregisterbeandefinitions (ele); }} org.springframework.beans.factory.xml.defaultbeandefinitiondocumentreader#processbeandefinition protected V OID Processbeandefinition (Element ele, beandefinitionparserdelegate delegate) {//parsing XML parsing process is explained in detail below Beandefi
        Nitionholder Bdholder = delegate.parsebeandefinitionelement (ele);
            if (Bdholder! = null) {Bdholder = delegate.decoratebeandefinitionifrequired (Ele, Bdholder);
                try {//Register the final decorated instance. Registering the Bean's adornment object BeandefinItionreaderutils.registerbeandefinition (Bdholder, Getreadercontext (). GetRegistry ()); } catch (Beandefinitionstoreexception ex) {Getreadercontext (). Error ("Failed to register bean
            Definition with Name ' "+ bdholder.getbeanname () +" ' ", Ele, ex);
            }//Send registration event.
        Register Event Getreadercontext (). firecomponentregistered (New Beancomponentdefinition (Bdholder)); }} org.springframework.beans.factory.support.beandefinitionreaderutils#registerbeandefinition public static Voi
            D registerbeandefinition (Beandefinitionholder Definitionholder, beandefinitionregistry Registry)
        Throws Beandefinitionstoreexception {//Register bean definition under primary name.
        String beanname = Definitionholder.getbeanname ();

   The real bean is registered to the container registry.registerbeandefinition (Beanname, Definitionholder.getbeandefinition ());     Register aliases for Beans name, if any.
        Registered alias string[] aliases = definitionholder.getaliases (); if (aliases! = null) {for (String aliase:aliases) {Registry.registeralias (Beanname, Aliase
            );
    }}}//Register for detailed processing org.springframework.beans.factory.support.defaultlistablebeanfactory#registerbeandefinition public void Registerbeandefinition (String beanname, Beandefinition beandefinition) throws Beandefinitionst
        oreexception {assert.hastext (beanname, "Bean name must not being empty");

        Assert.notnull (beandefinition, "beandefinition must not being null"); if (beandefinition instanceof abstractbeandefinition) {try {(abstractbeandefinition) Beande
            finition). Validate (); } catch (Beandefinitionvalidationexception ex) {throw new Beandefinitionstoreexception (Beande
  Finition.getresourcedescription (), Beanname,                      "Validation of Bean definition failed", ex); }} synchronized (This.beandefinitionmap) {Object oldbeandefinition = This.beandefinitionmap
            . get (Beanname); if (oldbeandefinition! = null) {if (!this.allowbeandefinitionoverriding) {throw new Beandefinitionstoreexception (Beandefinition.getresourcedescription (), Beanname, "Cannot regist  ER bean definition ["+ beandefinition +"] for beans ' "+ beanname +" ': there is already ["+
                Oldbeandefinition + "] bound."); } else {if (this.logger.isInfoEnabled ()) {This.logger.info ("  overriding bean definition for bean ' "+ beanname +" ': replacing ["+ Oldbeandefinition +
                    "] with [" + Beandefinition + "]");
 }}} or else {               This.beanDefinitionNames.add (Beanname);
            This.frozenbeandefinitionnames = null;

            } this.beanDefinitionMap.put (Beanname, beandefinition);
        Resetbeandefinition (Beanname);


 }
    }
b
Org.springframework.beans.factory.xml.beandefinitionparserdelegate#parsecustomelement (org.w3c.dom.Element) Public

beandefinition parsecustomelement (Element ele) {
        return parsecustomelement (ele, null);
    }

    Public beandefinition parsecustomelement (Element ele, beandefinition containingbd) {
        String NamespaceURI = Getnamespaceuri (ele);
        Namespacehandler handler = This.readerContext.getNamespaceHandlerResolver (). Resolve (NamespaceURI);
        if (handler = = null) {
            error ("Unable to locate Spring Namespacehandler for XML schema namespace [" + NamespaceURI + "] ", ele);
            return null;
        }
        Return Handler.parse (Ele, New ParserContext (This.readercontext, this, CONTAININGBD));
    }
parsing the data information process
Org.springframework.beans.factory.xml.beandefinitionparserdelegate#parsebeandefinitionelement ( org.w3c.dom.Element) public Beandefinitionholder parsebeandefinitionelement (Element ele, beandefinition
        Containingbean) {String id = ele.getattribute (id_attribute);

        String nameattr = Ele.getattribute (Name_attribute);
        list<string> aliases = new arraylist<string> (); if (Stringutils.haslength (nameattr)) {string[] Namearr = Stringutils.tokenizetostringarray (nameAttr, MULTI_VA
            Lue_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);
        } abstractbeandefinition beandefinition = Parsebeandefinitionelement (Ele, Beanname, Containingbean); if (beandefinition! = null) {if (!
                        Stringutils.hastext (Beanname)) {try {if (Containingbean! = null) { Beanname = Beandefinitionreaderutils.generatebeanname (beandefinition, This.readerc
                    Ontext.getregistry (), true);
                        } else {beanname = This.readerContext.generateBeanName (beandefinition); Register an alias for the plain Bean class name, if still possible,//if T
                        He generator returned the class name plus a suffix.
                        This is expected for Spring 1.2/2.0 backwards compatibility. String Beanclassname = Beandefinition.getbeanclAssname (); if (beanclassname! = null && beanname.startswith (beanclassname) && Beannam E.length () > Beanclassname.length () &&!this.readercontext.getregistry (). Isbean
                        Nameinuse (Beanclassname)) {Aliases.add (beanclassname); }} if (Logger.isdebugenabled ()) {Logger.debug ("neither X
                    ML ' id ' nor ' name ' specified-"+" using generated bean name ["+ Beanname +"] "); 
                    }} catch (Exception ex) {error (Ex.getmessage (), ele);
                return null;
            }} string[] Aliasesarray = Stringutils.tostringarray (aliases);
        return new Beandefinitionholder (Beandefinition, Beanname, Aliasesarray); } return Null } public abstractbeandefinition parsebeandefinitionelement (Element ele, String beanname, beandefinition cont

        Ainingbean) {This.parseState.push (new Beanentry (Beanname));
        String 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);

            } abstractbeandefinition bd = Createbeandefinition (className, parent);
            Parsebeandefinitionattributes (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));
        return BD;
        } catch (ClassNotFoundException ex) {error ("Bean class [" + ClassName + "] not found", Ele, ex); } catch (Noclassdeffounderror err) {error ("Class" 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;
 }
Encapsulation of Beans

Beandefinitionholder
    //bean Package Object
    private final beandefinition beandefinition;

    Bean Configuration name ID
    private final String beanname;
    Bean alias Group
    Private Final string[] aliases;
Beandefinition

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.