Spring Container--beanfactory

Source: Internet
Author: User
Tags xml reader

Spring container What is a spring container

The spring container is the core of spring, which can create objects, associate them together, configure individual objects, and manage the entire life cycle of each object. The spring container uses Dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans (an object is a bean).

There are two types of containers in spring:

① beanfactory is a simplest spring container that provides basic support for dependency injection (DI).

② ApplicationContext This container adds something that needs to be used by some businesses, more comprehensive. It contains the contents of the Beanfactory container.

Beanfactory container

In spring, there are a large number of implementation classes for Beanfactory interfaces (see), but the most commonly used is the Xmlbeanfactory class (in Eclipse, viewing its source can be seen as an obsolete class, but we also need to understand.) ), which can read configuration metadata from an XML file, which is used to generate a configured system or application.

  

                                   (Beanfactory interface Implementation Class)

Note:

  This article is focused on the following line of code to perform some of the things that happen in-depth exploration.

  Beanfactory beanfactory = new Xmlbeanfactory (new Classpathresource ("config file"));

Core class Introduction

Ⅰ. defaultlistablebeanfactory

The Xmlbeanfactory class inherits from the Defaultlistablebeanfacotry class, and the Defaultlistablebeanfactory class is the kernel part of the bean load and is the default implementation of spring registering and loading the bean.

The difference between the Xmlbeanfactory class and the Defaultlistablebeanfactory class is that a custom XML reader Xmlbeandefinitionreader is used in the Xmlbeanfactory class.

                            (Xmlbeandefinitionreader object)

A personalized Beandefinitionreader read is implemented, and the Defaultlistablebeafactory class inherits the Abstractautowirecapablebeanfactory class, The configurablelistablebeanfactory and Beandefinitionregistry interfaces are implemented.

      

                           (Defaultlistablebeanfactory Class)

The base class of the Defaultlistablebeanfactory class, implements some related class diagram of the interface:

    

                                    (Container loading section related class diagram)

The Xmlbeanfactory class inherits from the Defaultlistablebeanfactory class. The Xmlbeanfactory class extends the Defaultlistablebeanfactory class by using the Reader property to read and register resource files primarily in Xmlbeanfactory.

The construction method of the Xmlbeanfactory class is as follows:

    

                                   (Xmlbeanfactory construction method)

Ⅱ. Xmlbeandefinitionreader

      We already know the difference between the Xmlbeanfactory class and the Defaultlistablebeanfactory class, and a Xmlbeandefinitionreader object is defined in the Xmlbeanfactory class. Used to process a resource file.

The reading of the XML configuration file is very important for spring, because most of the functionality of spring is based on the configuration file, so we need to comb the approximate flow of resource file reads, parsing, and registration from the Xmlbeandefinitionreader class.

      

                                            (configuration file reads related classes)

Reading the relevant class diagram from the above configuration file can be read in the following general process:

      ① uses Resourceloader to convert the resource file path to the corresponding Resource file by inheriting from the method in Abstratcbeandefinitionreader.

② Convert the Resource file to a document file by converting the Resource file by Documentloader.

③ parses the document through the Defaultbeandefinitiondocumentreader class and uses Beandefinitionparserdelegate to parse the Element.

The above three steps are just a rough process of reading the configuration file, and the next step is to parse it in more detail.

    

Xmlbeanfactory

We already know the difference between xmlbeanfacotry and defaultlistablebeanfactory. Xmlbeanfactory structures such as:

                        

                               (Xmlbeanfactory class structure)

In spring, we create a configuration file, and after we have configured a bean in the configuration file, we are going to get the bean. In the test code we have written this code:

Xmlbeanfactory xmlbeanfactory = new Xmlbeanfacotry (new Classpathresource ("config file"));

It can also be:

Beanfactory beanfactory = new Xmlbeanfacotry (new Classpathresource ("config file"));

In summary, the above two lines of code are read configuration file creation container.

So what is the code for new Xmlbeanfacotry (new Classpathresource ("config file")? Let's take a look at the Xmlbeanfactory initialization sequence diagram below! (The picture is not good, will see it)

      

                                 (xmlbeanfactory initialization sequence diagram)

Timing Diagram parsing:

First, the sequence diagram starts with a test class, which is where the xmlbeanfactory is created.

Creating Xmlbeanfactory requires a Resource object, and because Resource is an interface, we use its implementation class Classpathresource to construct an instance object of the Resource resource file.

With the Resource object it is possible to initialize the xmlbeanfactory and finally get a beanfactory.

So, the question comes, what is resource? How does it encapsulate resources?

What is Resource?

        Before we say Resource, we need to know an interface:Inputstreamsource, which encapsulates any class that can return InputStream , such as file, Classpath resource, Byte, Array, and so on. It defines only one method: InputStream getInputStream () throws IOException; The method returns a InputStream object.

        The Resource interface abstracts all the underlying resources that are used within Spring: File, URL, Classpath, and so on. The methods and approximate functions of the Resource interface are as follows:

       

                            (Resource interface)

For resource files of different sources, there are Resource implementations of objects:

Files (filesystemresource), classpath Resources (classpathresource), URL resources (urlresource), and so on.

      

                           (Resource file Processing section related classes)

The loading of resource files is also often used in daily development, using the classes provided by Spring directly, such as using the following code when loading a file:

Resource Resource = new Classpathresource ("Resource file");

InputStream InputStream = Resource.getinputstream ();

Once we get inputstream, we can develop it in the way we used to, and we can use Resource and some of its implementation classes.

When the configuration file is encapsulated by Resource related classes, the read of the configuration file is Xmlbeandefinitionreader to complete.

Now that we know that Spring will encapsulate the configuration file as a Resource object, continue to understand the xmlbeanfactory initialization process. As you can see from the above Xmlbeanfactory class structure diagram, there are two construction methods for the Xmlbeanfactory class, such as:

    

                             (Xmlbeanfactory class construction method)

From what we see, the first constructor method internally invokes another constructor method inside the class. So, we also understand the second construction method.

First, a code like Super (Parentbeanfactory) appears in the first line, calling a constructor of the parent class (Defaultlistablebeanfactory).

      

                            (Defaultlistablebeanfactory with the method of construction)

To the parent class constructor method, we find that we continue to invoke the constructor of the parent class (Abstractautowirecapablebeanfactory), see:

      

                                 (Abstractautowirecapablebeanfactory class construction method)

As can be seen, the method of the construction of the argument (we use a parameter structure) first called a non-parametric construction method in this class, the non-parametric construction method first executes the parent class (Abstractbeanfactory) construction method (an empty method), here to understand Ignoredependencyinterface method, the main function of this method is to ignore the automatic connection of a given dependency interface (ignoring the automatic assembly function of a given interface). So what's the use of this method?

For example, if attribute B is in Class A, spring will automatically initialize B if property B is not initialized when it gets the Bean of a (which is also an important feature of spring). However, in some cases, B is not initialized, for example, B implements the Beannameaware interface. Introduction to the Spring API: The application context typically uses it to register dependencies that are resolved in other ways, such as through the beanfactoryaware implementation of the Beanfactory or through the applicationcontextaware implementation of the ApplicationContext. By default, only the Beanfactoryaware interface is ignored. to ignore other types, call this method for each type.

Finally, call the Setparentbeanfactory method to set the Beanfactory object.

      

                               (Setparentbeanfactory method)

There is an if judgment in the Setparentbeanfactory method that determines whether the beanfactory is already associated and throws an exception if it is already associated.

      

Load Bean

      When we talk about Resource, we know how xmlbeanfactory is constructed, and we know that one of the constructor methods calls the constructor of the parent class first, so the super () statement is The invocation of the This.reader.loadBeanDefinitions (Resource) method. This method is the starting point for the entire resource load, and here is the timing diagram for the method call:

    

                                  (loadbeandefinitions method execution sequence diagram)

As you can see, the invocation of this method has caused a lot of work. But these jobs are just getting ready, so here's what we're going to do:

          (1) encapsulates the resource file . When the Loadbeandefinitions method is called, it jumps to the method, which invokes an overloaded method of this class, and creates a Encodedresource object as a parameter, based on the Resource object, using the The role of Encodedresource is to encapsulate Resource using the Encodedresource class   .

            

                                (Loadbeandefinitions (Resource Resource) method)

(2) get the input stream build InputSource. Get the corresponding inputstream from the Resource and create the InputSource.

            

                      (Loadbeandefinitions (Encodedresource Encodedresource) method to get InputStream and create InputSource)

(3) continue calling the Doloadbeandefinitions () method through the InputSource object and Resource that you just created .

              

                               (Doloadbeandefinitions (InputSource, Resource) method invocation)

Above, we see encodedresource many times, so, what is it exactly?

Encodedresource

    By name you can guess that the class is related to the encoding. This class is mainly about the encoding of the resource file to be processed. One of the most important methods of the Getreader () method is that when the encoding attribute is set, Spring uses the corresponding encoding as the input stream encoding .

First look at one of its construction methods: (There are four constructor methods in this class, but the rest of the three constructors call the following constructor method)

      

                             (A construction method of the Encodedresource class)

The construction method is primarily to initialize the properties in the class.

Look again at the Getreader () method:

          

                               (Getreader () method)

      The Getreader () method constructs a inputstreamreader with encoding. Once the Resource is encapsulated as a Encodedresource object, it comes to the loadbeandefinitions () method in the Xmlbeandefinitionreader class (another overloaded method). That is the method in.

      

                                (Loadbeandefinitions (Encodedresource.) Method part important Code)

method is the real data preparation, which is the part described in the 7th sequence diagram.

Again review the above data Preparation section, first the incoming Resource object encapsulated as Encodedresource, why need encapsulation? The purpose is to consider the possible coding requirements of Resource, second, to prepare the InputSource object by sax reading the XML file, and finally to pass the prepared data through the parameters to the core processing method Doloadbeandefinitions ( InputSource InputSource, Resource Resource). Here's a look at what the Doloadbeandefinitions () method does:

      

                           (Doloadbeandefinitions () method part code (except catch section))

Doloadbeandefinitions () method There are several catch behind the try, except for these catch, so this code does the following three things:

(1) get the validation mode for the XML file

(2) loading the XML file to get the corresponding Document object

(3) registering Bean information against the returned Document object

The above three operations support the implementation of the entire spring container, and the following will begin with these three steps.

    • Get the validation mode for XML

The role of the XML validation pattern: To ensure the correctness of the XML file (seemingly the constraint), there are two common authentication modes:DTD(Document Type Definition) and XSD(XML Schemas Definition). Learn more about verification mode please search by yourself online.

In the previous (Doloadbeandefinitions method code) diagram, we saw that the first line of code in the try block was: Document document = Doloaddocument (InputSource, Resource); The Doloaddocument () method in this class is called, but the code is primarily used to get the document object, which is the second thing above, but in which the XML file validation pattern is obtained first .

      

                          (Doloaddocument () method)

As we can see, when the Loaddocument () method executes, the Getvalidationmodeforresource (Resource) method is executed first, and the method returns a value of type int. (In Spring3.2, there is no doloaddocument () method, which calls the Getvalidationmodeforresource (Resource) method directly in the Doloadbeandefintions () method and Loaddocument () method), let's look at what the Getvalidationmodeforresource (Resource) method does:

      

                              (Getvalidationmodeforresource (Resource) method)

In the above method, several constants are used, which are the values represented by several constants:

      

           (Several constants in the Org.springframework.util.xml.XmlValidationModeDetector Class)

      Note: The Xmlbeandefinitionsreader class also has a constant with the same name in addition to the DOCTYPE constant, whose value is the value above . that is, Spring uses different values for different validation modes .

In the second picture above , it is learned that the Getvalidationmodeforresource (Resource) method first determines whether the validation mode is manually specified (through the Setvalidationmode () method setting the validation mode), and the method of judging is to obtain The Validationmode attribute is determined. Otherwise, automatic detection is used to automatically detect calls to the Org.springframework.beans.factory.xml.XmlBeanDefinitionReader.detectValidationMode (resource ) method (The method in this class) is implemented .

      

                      (The Xmlbeandefinitionreader.detectvalidationmode (Resource) method omits the catch processing part of the code)

In the last try block called the Detectvalidationmode (InputStream) method in the Xmlvalidationmodedetector class for further processing, the following is a look at this method (here, if you want to fully understand, It is recommended to check the source code, after all, in the method also called other methods, but also used a few constants, not listed here.

      

                           (Detectvalidationmode (InputStream) method in the Xmlvalidationmodedetector class)

The section on obtaining the validation pattern above needs to be understood based on the DTD and XSD, because getting the validation pattern is based on the use of two authentication modes. Spring detects the validation mode by determining whether it contains DOCTYPE, or XSD if it is included (this is what you can see from the first line of the above diagram: viewing the file to find DOCTYPE), which can be easily seen in the method.

Here, get the verification mode and the explanation is done.

    • Get Document

Above we know that before acquiring the Document, we need to get the XML validation mode first. Let's take a look at how the Document was retrieved in Spring. In the above (Doloaddocument () method) diagram We see that the Doloaddocument method invokes the Loaddocuemnt () method of this class Documentloader. Documentloader is defined as follows:

Private Documentloader Documentloader = new Defaultdocumentloader ();

Documentloader is an interface, so use its implementation class Defaultdocumentloader;

Let's take a look at the loaddocument () method in the Defaultdocumentloader class.

      

                            (Loaddocument () method)

The above code is basically parsing XML through SAX, which is a basic step. the Documentbuilderfacotry object is created first, the Documentbuilder is created through Documentbuilderfactory, and then the InputSource is parsed to return the Document object . This involves the XML parsing related knowledge, can go to the Internet in-depth understanding.

   • Analysis and Registration beandefinitions

In the above (Doloadbeandefinitions () method) diagram we know that after acquiring the Document, the following line of code is executed:

Return Registerbeandefinitions (Doc, Resource);

that is, continue calling the Registerbeandefinitions (Doc, Resource) method.

                                  (Registerbeandefinitions (Doc, Resource) method)

The first line of code in the Beandefinitiondocumentreader,beandefinitiondocumentreader is to create the interface, and the instantiation is The Createbeandefinitiondocumentreader () method is done, and by executing this method, the Beandefinitiondocumentreader real type is Defaultbeandefinitiondocumentreader (Its implementation class).

The third line is loading, registering the bean, because Beandefinitiondocumentreader is the interface, so we came to the Defaultbeandefinitiondocumentreader class Registerbeandefinitions () method.

      

                             (Registerbeandefinitions (Document, Xmlreadercontext) method)

One of the important purposes of the method is to extract root and continue the Beandefinition registration as a parameter.

      

                           (Doregisterbeandefinitions (Element) method)

The profile property is involved in the code, and the property details are also available on the Internet. In the second part of the program, the program first gets whether the Beans node defines the profile property, and if it is defined, it needs to be found in the environment variable Central, and each definition is not resolved.

You can begin to read the XML by processing the profile, and look at the box method Parsebeandefinitions (Root, This.delegate).

    

                            (Parsebeandefinitions (Element, beandefinitionparserdelegate) method)

     The default bean declaration can be used in Spring's XML file, or it can be customized. So Spring does a different processing for different Bean declarations.

The parsing of the Bean label is described later. Until this point, the above content is just Spring loading the config file, and has not really started parsing the bean tag. Just an introduction to the Spring container.

PS: This article has many shortcomings, hope to point out!

Spring Container--beanfactory

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.