Spring Source Learning-bean Loading

Source: Internet
Author: User

1. Scene

A applicationcontext.xml configuration file, this is not a few
A bean, here I do not use interface, directly with a normal class as a spring bean
A JUnit test class


Applicationcontext.xml<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd BEAN 2.0//en" "Http://www.springframework.org/dtd/spring-beans-2.0.dtd" >
<beans>
<bean id= "Studentbean" class= "My. Studentbean "></bean>
</beans>
Studentbeanpublic class studentbean{
public void GetName (String name) {
System.out.println ("Your name is:" + name);
}
}


Unit Test class

1 public class MyTest {
2
3 public static void main (string[] args) {
4 Classpathresource res = new Classpathresource ("My/applicationcontext.xml");
5
6 xmlbeanfactory bf = new Xmlbeanfactory (res);
7
8 Studentbean bean = (studentbean) bf.getbean ("Studentbean");
9
Ten Bean.getname ("Yangay");
11}
12}

Run the unit test and print out "Your name is: Yangay", the test class has only four lines of code, but what does spring do for us? Here we analyze the bean loading process based on this scenario.

2. Preliminary analysis

(1) Get configuration file Classpathresource res = new Classpathresource ("My/applicationcontext.xml"); This sentence is simply read into the configuration file and encapsulates the resource object provided by spring for later logic use.
Within spring, there are over 10 classes or files ending in resource that deal with different types of resource files, such as Filesystemresource, Classpathresource, Urlresource, and so on, with a similar process, Internal details don't have to be cared for, it's almost nothing to do with other component logic.
(2) parsing the configuration file and registering the bean xmlbeanfactory bf = new Xmlbeanfactory (res); The logic in this is quite complex, involving many factory, Reader, Loader, Beandefinition, Perser, Registry series interfaces and classes, But the basic thing they do is to make the bean information of applicationcontext.xml configuration Beandefinition object, and then put it in factory map (this step is called registration), so that the program can take the bean information directly from the factory.
To track this process, the general process is as follows:
A. When constructing xmlbeanfactory, the Loadbeandefinitions method of the reader object is called to load the bean definition information
B. In the reader object's Doloadbeandefinitions authentication document (configuration file) mode, and then through the Documentloader object processing resource object, generate our Document object;
C. Call the doregisterbeandefinitions of the Beandefinitiondocumentreader object to register the bean definition information;
D. parsebeandefinitions recursively loops through the nodes from the root of the XML document, delegating the real processing of the bean nodes to the beandefinitionparserdelegate, Method Parsebeandefinitionelement transforms a bean node into a Beandefinitionholder object, which is the final parsing process;
E. Defaultlistablebeanfactory.registerbeandefinition uses the analytic good Beandefinition object completes the final registration, actually is puts Beanname and the beandefinition as the key value pair to BEANFAC Map of the Tory object;
(3) Instantiating beans
Studentbean bean = (studentbean) bf.getbean ("Studentbean"); This step is also complicated by spring, but the rationale is to use the reflection mechanism to create an instance of a bean from the Bean's Class attribute, in which case a Studentbean object is created.
(4) The method of invoking the object, there is nothing to say. Of course, if the method does a statement such as transactions, AOP, this step is not so easy to deal with.

3. Parse the configuration file and register the bin object

We analyze the bean registration process, which is the following line of code, he completed the configuration file parsing and bin registration function, we look at how much spring has done for us.
xmlbeanfactory bf = new Xmlbeanfactory (res);
public class Xmlbeanfactory extends Defaultlistablebeanfactory {
Here, a default bean definition reader is defined for the container
Private final Xmlbeandefinitionreader reader = new Xmlbeandefinitionreader (this);
Public xmlbeanfactory (Resource Resource) throws Beansexception {
This (resource, null);
}
The reader is used in the initialization function to read the resource and get the bean definition information.
Public Xmlbeanfactory (Resource Resource, Beanfactory parentbeanfactory) throws Beansexception {
Super (Parentbeanfactory);
This.reader.loadBeanDefinitions (Resource);
We followed in and found that he actually called the Loadbeandefinitions method of the Xmlbeandefinitionreader object. 3.1 xmlbeandefinitionreader.loadbeandefinitionspublic int loadbeandefinitions (Resource Resource) throws beandefinitionstoreexception {
Encapsulating resource Files
Return Loadbeandefinitions (New Encodedresource (Resource));
}
InputStream InputStream = Encodedresource.getresource (). getInputStream ();
try {
InputSource InputSource = new InputSource (InputStream);
if (encodedresource.getencoding () = null) {
Inputsource.setencoding (Encodedresource.getencoding ());
}
Return Doloadbeandefinitions (InputSource, Encodedresource.getresource ());
This method is the entry point for the entire resource load, so let's take a look at the process of this approach: a. Encapsulating resource Files
New Encodedresource (Resource)
B. Getting the input stream
Get InputStream from the Encodedresource object and construct the InputSource object
C. Then call the Doloadbeandefinitions method to complete the specific loading process 3.2 Doloadbeandefinitions method
int validationmode = Getvalidationmodeforresource (Resource);
Document doc = this.documentLoader.loadDocument (InputSource, Getentityresolver (), This.errorhandler, Validationmode, Isnamespaceaware ());
Return Registerbeandefinitions (Doc, Resource); The code for this method is very long, if you do not consider exception handling, actually only do three things: a. Gets the validation mode for the XML file
B. Load the XML file and get the corresponding Document object
C. Registering bean information based on the returned Document object
The validation mode is not discussed here;
The loading process of the Document object is not discussed here;
Here go directly to the bean registration method registerbeandefinitions
3.3 Registerbeandefinitions method public int registerbeandefinitions (Document doc, Resource Resource) throws Beandefinition storeexception {
This defines the parser, using Xmlbeandefinitionparser to parse the bean definition file of the XML way-the current version does not use this parser, using the Xmlbeandefinitionreader
if (this.parserclass! = null) {
Xmlbeandefinitionparser parser =
(Xmlbeandefinitionparser) Beanutils.instantiateclass (This.parserclass);
Return Parser.registerbeandefinitions (this, doc, Resource);
}
The specific registration process, first get xmlbeandefinitionreader, to process the XML Bean definition file
Beandefinitiondocumentreader Documentreader = Createbeandefinitiondocumentreader ();
int countbefore = Getbeanfactory (). Getbeandefinitioncount ();
Documentreader.registerbeandefinitions (Doc, Createreadercontext (Resource));
Return Getbeanfactory (). Getbeandefinitioncount ()-Countbefore;
When converting documents to document objects, extracting and registering beans is our highlight.
Instead of seeing the code we wanted, we delegated the work to the Beandefinitiondocumentreader object to handle 3.4 Beandefinitiondocumentreader.doregisterbeandefinitions method
public void Registerbeandefinitions (Document doc, Xmlreadercontext readercontext) {
This.readercontext = Readercontext;
Element root = Doc.getdocumentelement ();

Beandefinitionparserdelegate delegate = Createhelper (Readercontext, Root);
Preprocessxml (root);
Parsebeandefinitions (Root, delegate);
Postprocessxml (root);
}
protected void Parsebeandefinitions (Element root, beandefinitionparserdelegate delegate) {
if (Delegate.isdefaultnamespace (Root.getnamespaceuri ())) {
This gets the child nodes of the XML file, such as the individual bean nodes
NodeList nl = root.getchildnodes ();
This is where each node is analyzed and processed
for (int i = 0; i < nl.getlength (); i++) {
Node node = Nl.item (i);
if (node instanceof Element) {
Element ele = (element) node;
String NamespaceURI = Ele.getnamespaceuri ();
if (Delegate.isdefaultnamespace (NamespaceURI)) {
Here is the invocation of the parsing process, parsing the default elements such as the bean element
Parsedefaultelement (Ele, delegate);
}else {
Delegate.parsecustomelement (ele);
}
}
}
} else {
Delegate.parsecustomelement (root);
}
} After difficulties and hardships, the road 18 Bend, we finally went to the core of the logic of the bottom doregisterbeandefinitions, if said before has been the XML load parsing preparation phase,
So this approach is really starting to parse, and the core part of what we're looking for is really starting. The code for this method is familiar to us, reading the Document object, looping through each bean node, and then processing.
Spring has two types of beans, one is the default and the other is a custom bean, and this method calls different methods for processing. 3.5 Processbeandefinition method for handling default labels
protected void Processbeandefinition (Element ele, beandefinitionparserdelegate delegate) {
Beandefinitionholder Bdholder = delegate.parsebeandefinitionelement (ele);
if (Bdholder! = null) {
Bdholder = delegate.decoratebeandefinitionifrequired (Ele, Bdholder);
Beandefinitionreaderutils.registerbeandefinition (Bdholder, Getreadercontext (). GetRegistry ());
Getreadercontext (). firecomponentregistered (New Beancomponentdefinition (Bdholder));
}
}a. First, using the Parsebeandefinitionelement method of the delegate class to parse the element, return the Beandefinitionholder object Bdholder, after this method, The Bdholder instance already contains all the configuration information for the bean in our configuration file, such as name, class, and so on.
B. Decorating the Bdholder
C. After the resolution is completed, to register the Bdholder, similarly, the registration process entrusted to Beandefinitionreaderutils to deal with 3.6 delegate.parsebeandefinitionelement (ele)
This method is the whole process of parsing the default label, and he converts an element node into a Beandefinitionsholder object, where the properties in Ele and Bdholder correspond. We have seen it both commonly and infrequently, although some complex attributes need to be further parsed, without compromising our excitement.
A. Extracting the ID and Name property of an element
B. Further parsing of all other properties and uniform encapsulation to instances of the Beandefinition type
C. Encapsulating the acquired information in a Beandefinitionholder instance to be continued ... String id = ele.getattribute (id_attribute);
String nameattr = Ele.getattribute (Name_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);

return new Beandefinitionholder (BD, Beanname, Aliasesarray); Follow in, we see the bottom of the analysis, such as parsemetaelements, here no further analysis.
For the configuration file, parsing is finished, decoration is finished, the XML has been encapsulated in the attributes of the bean element to the Beandefinition object, has been able to meet the requirements of subsequent use, the remaining work is the registration of the beandefinition. 3.7 Beandefinitionreaderutils.registerbeandefinition
This method does not do too much, but calls the Beandefinitionregistry registration method directly. Beandefinitionregistry is an interface with multiple implementation classes, where we use the default implementation defaultlistablebeanfactory. 3.8 Defaultlistablebeanfactory.registerbeandefinition
Code wordy a lot of, in fact, so-called registration, is to put the Beanname and Beandefinition objects as the key value pair to Beanfactory object Beandefinitionmap.
But spring often writes the simple logic very "verbose", analyzes the code carefully, and discovers that he has accomplished several things:
A. Checking the Bean object
B. Check if a bean with the same name already exists in the beanfactory, and if so, handle it accordingly
C. Put the Bean object in the Beandefinitionmap (this is the final so-called registration)
D. Clearing the entire process cache for object data

The above is spring's whole process of bean parsing registration, summarizing the approximate steps:
1. Load the XML file and encapsulate it as a resource object
2. Call the Reader object method to read the contents of the XML file and place the related attributes on the Beandefinition instance
3. Place the Beandefinition object in the Beanfactory object

4. Instantiating beans

Detailed procedures, reserved locations

Spring Source Learning-bean Loading

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.