Spring Framework in-depth--IOC container initialization--load resolution for bean-defined resources

Source: Internet
Author: User
The Bean defines the load resolution of the resource, resource is the resource descriptor for the XML file (Resource descriptor)

back to Xmlbeandefinitionreader's Loadbeandefinitions (Resource ...) Method

Xmlbeandefinitionreader.java @Override public int loadbeandefinitions (Resource Resource) throws Beandefinitionstoreex
    ception {//The XML resource read in is specially encoded to return Loadbeandefinitions (new Encodedresource (Resource));
     }/** * Load bean definitions from the specified XML file. * @param encodedresource The resource descriptor for the XML file, * allowing to specify a encoding to use for Parsi ng the file * @return the number of beans definitions found * @throws beandefinitionstoreexception in case of LOA Ding or parsing errors */public int loadbeandefinitions (Encodedresource encodedresource) throws Beandefinitionst Oreexception {... try {//Get resource Resource io stream InputStream InputStream = Encodedre
            Source.getresource (). getInputStream (); try {//wraps InputStream into InputSource parsing stream InputSource InputSource = new InputSource (Inputstrea
                m); if (encodedresOurce.getencoding ()! = null) {inputsource.setencoding (encodedresource.getencoding ()); }//Here is the process of actually handling resource return doloadbeandefinitions (InputSource, Encodedresource.getreso
            Urce ());
            } finally {inputstream.close ();

}
        }
        ......
    } protected int doloadbeandefinitions (InputSource inputsource, Resource Resource) throws Beandefinitionstoreexce ption {try {//transforms an XML file into a DOM object, the parsing process is implemented by Documentloader document doc = Doloaddocument (inputso
            Urce, Resource);
        Initiates parsing of the Document object return Registerbeandefinitions (Doc, Resource);

}
        ......
    } Protected Document doloaddocument (InputSource inputsource, Resource Resource) throws Exception {//documentloader will
 Resource parses into a DOM object and returns return This.documentLoader.loadDocument (InputSource, Getentityresolver (), This.errorhandler,               Getvalidationmodeforresource (Resource), Isnamespaceaware ()); }

Documentloader Converting a bean definition resource resource to a Document object

Defaultdocumentloader.java

//Use the standard JAXP parser to parse the loaded Bean definition resource into a DOM document instance public
Document loaddocument ( InputSource InputSource, Entityresolver entityresolver,
            errorhandler errorhandler, int validationmode, Boolean Namespaceaware) throws Exception {
        //Create File Parser factory
        documentbuilderfactory factory = createdocumentbuilderfactory (Validationmode, namespaceaware);
        if (logger.isdebugenabled ()) {
            logger.debug ("Using JAXP provider [" + Factory.getclass (). GetName () + "]");
        }
        Create document resolver
        Documentbuilder builder = Createdocumentbuilder (Factory, Entityresolver, ErrorHandler);
        Parse Bean definition Resource
        return builder.parse (InputSource);
    }

The parsing process calls the Java EE Standard JAXP standard for processing.
At this point the spring IOC container defines the resource file according to the positioned Bean, and the process of loading it into and converting it into a Document object is complete.

After the

is converted to a Document object, Xmlbeandefinitionreader delegates Defaultbeandefinitiondocumentreader to perform the actual parsing work

xmlbeandefinitionreader.java//register the bean definitions contained in the given DOM documen T. public int registerbeandefinitions (Document doc, Resource Resource) throws Beandefinitionstoreexception {B
        Eandefinitiondocumentreader Documentreader = Createbeandefinitiondocumentreader ();
        int countbefore = GetRegistry (). Getbeandefinitioncount (); Beandefinitiondocumentreader is just an interface,//actually delegated to Defaultbeandefinitiondocumentreader for parsing documentreader.regist
        Erbeandefinitions (Doc, Createreadercontext (Resource));
    Return GetRegistry (). Getbeandefinitioncount ()-Countbefore; } protected Beandefinitiondocumentreader Createbeandefinitiondocumentreader () {return beandefinitiondocumentr
    Eader.class.cast (Beanutils.instantiateclass (This.documentreaderclass)); } private class<?> documentreaderclass = Defaultbeandefinitiondocumentreader.class; 

The

Beandefinitiondocumentreader interface calls its implementation class Defaultbeandefinitiondocumentreader the document object through the Registerbeandefinitions method. Row parsing

Defaultbeandefinitiondocumentreader.java public void Registerbeandefinitions (Document doc, Xmlreadercontext
        Readercontext) {this.readercontext = Readercontext;
        Logger.debug ("Loading bean Definitions");
        Element root = Doc.getdocumentelement ();
    Doregisterbeandefinitions (root); } protected void Doregisterbeandefinitions (Element root) {//any nested <beans> elements would cause recurs Ion in the 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 Ultimatel
        Y Reset This.delegate back to its original (parent) reference.
        This behavior emulates a stack of delegates without actually necessitating one.
        Beandefinitionparserdelegate parent = this.delegate; The specific parsing process consists of BeandefinitionparserdeLegate implements various elements of the spring bean definition XML file defined in//beandefinitionparserdelegate this.delegate = CreateDelegate (getreade

        Rcontext (), root, parent);
            if (This.delegate.isDefaultNamespace (root)) {String Profilespec = Root.getattribute (Profile_attribute); if (Stringutils.hastext (Profilespec)) {string[] specifiedprofiles = Stringutils.tokenizetostringa
                Rray (Profilespec, beandefinitionparserdelegate.multi_value_attribute_delimiters);
                if (!getreadercontext (). Getenvironment (). Acceptsprofiles (Specifiedprofiles)) {return;
        }}}//Before parsing the bean definition, perform custom parsing to enhance the extensibility of the parsing process preprocessxml (root);
        Parses the bean-defined Document object from the root element of document Parsebeandefinitions (root, this.delegate);

        After parsing the bean definition, a custom parsing is performed to enhance the extensibility of the parsing process postprocessxml (root);
    This.delegate = parent; } protected Beandefinitionparserdelegate CREAtedelegate (Xmlreadercontext readercontext, Element root, beandefinitionparserdelegate parentdelegate) {
        Beandefinitionparserdelegate delegate = new Beandefinitionparserdelegate (readercontext);
        Delegate.initdefaults (Root, parentdelegate);
    return delegate; }

The flowchart above is as follows:
Bean Definition Resource Loading parsing ">

the core function of the parsing process is parsebeandefinitions (Element root, beandefinitionparserdelegate delegate)

Defaultbeandefinitiondocumentreader.java//parse The elements at the root level in the document protected void Parsebeand Efinitions (Element root, Beandefinitionparserdelegate delegate) {///The root node uses the spring default XML namespace//beandefinit
        Ionparserdelegate defines a constant, String Beans_namespace_uri = "Http://www.springframework.org/schema/beans";
            if (Delegate.isdefaultnamespace (root)) {NodeList nl = root.getchildnodes ();
                for (int i = 0; i < nl.getlength (); i++) {Node node = Nl.item (i);
                    Whether the element node uses the default XML namespace if (node instanceof Element) {element ele = (element) node;
                        if (Delegate.isdefaultnamespace (ele)) {//Parse element nodes using spring's bean rules
                    Parsedefaultelement (Ele, delegate); } else {//does not use the spring default XML namespace, the element node is parsed using a user-defined parsing rule de Legate.parsecustomElement (ele); {}}}}}} else {//document's root node does not use the spring default namespace, the user-defined parsing rules are used to resolve the docu
        ment root node delegate.parsecustomelement (root); }}//Use spring's bean rules to parse the document element node private void Parsedefaultelement (element ele, Beandefinitionparserdelegate Delegat e) {//Element node is <Import> if (delegate.nodenameequals (Ele, import_element)) {Importbeandefin
        Itionresource (ele); }//Element node is <Alias> else if (delegate.nodenameequals (Ele, alias_element)) {Processaliasreg
        Istration (ele); }//Element node is <Bean> else if (delegate.nodenameequals (Ele, bean_element)) {Processbeandefini
        tion (ele, delegate); }//Element node is <Beans> else if (delegate.nodenameequals (Ele, nested_beans_element)) {//recur
        Se recursive doregisterbeandefinitions (ele); }
    }

<Import> and <Alias> element parsing has been completed in Defaultbeandefinitiondocumentreader, and the most used <Bean> in the Bean definition resource file The element is referred to Beandefinitionparserdelegate to parse, the source code is as follows

defaultbeandefinitiondocumentreader.java protected void processbeandefinition (Element ele , Beandefinitionparserdelegate delegate) {Beandefinitionholder Bdholder = delegate.parsebeandefinitionelement (ele
        );
            if (Bdholder! = null) {Bdholder = delegate.decoratebeandefinitionifrequired (Ele, Bdholder);
                try {//Register the final decorated instance.
            Beandefinitionreaderutils.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 (New Beancomponentdefinition (Bdholder)); }
    }
Beandefinitionparserdelegate.java

//parsing <Bean> element entry public
Beandefinitionholder Parsebeandefinitionelement (Element ele) {
        return parsebeandefinitionelement (ele, null);
    }
Parses the <Bean> element in the Bean definition resource file, which mainly handles the Id,name and alias properties of the <Bean> element public 
Beandefinitionholder Parsebeandefinitionelement (element ele, beandefinition Containingbean) 
//Detailed parsing of other properties of the Bean definition configured in the <Bean> element, Attribute data other than Id,name and alias attribute three public  
abstractbeandefinition parsebeandefinitionelement (
            Element ele, String Beanname, Beandefinition Containingbean)

Note that during the parsing process, the corresponding definition class beandefinition is created based on the configuration information of the element, no bean objects are created and instantiated, and dependency injection uses these record information to create and instantiate specific Bean objects <Bean> Common Properties configuration: ID, name, alias, and property

The space is larger ... Stay until later to learn more. registering with the IOC container beandefinition

After parsing the bean definition resource through the Spring IOC container, the IOC container has roughly completed the preparation for managing the Bean object, the initialization process, but the most important dependency injection has not yet occurred. Now that the beandefinition stored in the IOC container is just some static information, the next step is to register the bean definition information with the container to complete the IOC container initialization process.
back to Defaultbeandefinitiondocumentreader's processbeandefinition function , When the Beandefinitionparserdelegate function of Beandefinitionparserdelegate is complete, the Beandefinitionhold object that encapsulates Beandefinition is returned, and the next, Call Beandefinitionreaderutils's Registerbeandefinition method to register the parsed bean with the IOC container.
Function call Flowchart:
Bean definition Load Parse for resource ">

Defaultbeandefinitiondocumentreader.java protected void Processbeandefinition (Element ele, 
        Beandefinitionparserdelegate delegate) {Beandefinitionholder Bdholder = delegate.parsebeandefinitionelement (ele);
            if (Bdholder! = null) {Bdholder = delegate.decoratebeandefinitionifrequired (Ele, Bdholder);
                try {//Register the final decorated instance. Register Beandefinition's entrance to the container beandefinitionreaderutils.registerbeandefinition (Bdholder, Getreadercontext
            (). GetRegistry ()); } catch (Beandefinitionstoreexception ex) {Getreadercontext (). Error ("Failed to register bean
            Definition with Name ' "+ bdholder.getbeanname () +" ' ", Ele, ex);
            }//Send registration event.
        After registration is complete, send the registration event Getreadercontext (). firecomponentregistered (New Beancomponentdefinition (Bdholder)); }
    }

To be Continued ...

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.