Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring Container BeanFactory

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to use Spring container BeanFactory". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use Spring Container BeanFactory.

Spring Container what is a Spring container

The Spring container is the core of Spring, creating objects, associating them together, configuring individual objects, and managing the entire lifecycle 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 the simplest Spring container that provides basic support for dependency injection (DI).

② ApplicationContext this container adds something that the enterprise needs to be more comprehensive. It contains what is in the BeanFactory container.

BeanFactory container

In Spring, there are a large number of implementation classes for the BeanFactory interface (see figure below), but the most commonly used is the XmlBeanFactory class (in Eclipse, looking at its source code shows that it is already an outdated class, but we also need to know. Which can read configuration metadata from an XML file to generate a configured system or application

(BeanFactory interface implementation class)

Note:

This article focuses on some in-depth exploration of what happens when the following line of code is executed.

BeanFactory beanFactory = new XmlBeanFactory (new ClassPathResource ("profile"))

Introduction to core classes

Ⅰ. DefaultListableBeanFactory

The XmlBeanFactory class inherits from the DefaultListableBeanFacotry class, while the DefaultListableBeanFactory class is the core part of Bean loading and is the default implementation of Spring registration and loading Bean.

The difference between the XmlBeanFactory class and the DefaultListableBeanFactory class is that the custom XML reader XmlBeanDefinitionReader is used in the XmlBeanFactory class

(XmlBeanDefinitionReader object)

The personalized BeanDefinitionReader reading is realized, and the DefaultListableBeaFactory class inherits the AbstractAutoWireCapableBeanFactory class, and implements ConfigurableListableBeanFactory and BeanDefinitionRegistry interfaces.

(DefaultListableBeanFactory class)

The base class of the DefaultListableBeanFactory class, and some related class diagrams that implement the interface:

(container loading part of the related class diagram)

The XmlBeanFactory class inherits from the DefaultListableBeanFactory class. The XmlBeanFactory class extends the DefaultListableBeanFactory class, which mainly uses the reader property to read and register resource files 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, where a XmlBeanDefinitionReader object is defined in the XmlBeanFactory class to process the resource file.

The reading of XML configuration files is very important for Spring, because most of the functions of Spring are based on configuration files, so we need to comb through the general process of reading, parsing, and registering resource files from the XmlBeanDefinitionReader class.

(configuration file reads related classes)

By reading the relevant class diagram from the above configuration file, you can get the following general reading process:

① uses ResourceLoader to convert the path of the resource file to the corresponding Resource file through a method inherited from AbstratcBeanDefinitionReader.

② converts Resource files through DocumentLoader and converts Resource files into Document files.

③ parses Document through the DefaultBeanDefinitionDocumentReader class and uses BeanDefinitionParserDelegate to parse Element.

The above three steps are just a rough process of reading the configuration file, which will be parsed in more detail.

XmlBeanFactory

We already know the difference between XmlBeanFacotry and DefaultListableBeanFactory. The structure of XmlBeanFactory is shown below:

(XmlBeanFactory class structure)

In Spring, after we have created a configuration file and configured a Bean in the configuration file, we will get the Bean. In the test code, we all wrote this line of code:

XmlBeanFactory xmlBeanFactory = new XmlBeanFacotry (new ClassPathResource ("profile"))

It can also be:

BeanFactory beanFactory = new XmlBeanFacotry (new ClassPathResource ("profile"))

In short, the above two lines of code is to read the configuration file to create the container.

So what about the new XmlBeanFacotry (new ClassPathResource ("configuration file") code? First take a look at the following XmlBeanFactory initialization sequence diagram! (the painting is not good, so just look at it.)

(XmlBeanFactory initialization sequence diagram)

Analysis of time sequence diagram:

◆ first, the timing diagram starts with a test class that is where the XmlBeanFactory was created above.

◆ needs a Resource object to create XmlBeanFactory, and since Resource is an interface, we use its implementation class ClassPathResource to construct an instance object of the Resource resource file.

◆ can initialize XmlBeanFactory with the Resource object, and finally get a BeanFactory.

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

What is ● Resource?

Before we talk about Resource, we need to know an interface: InputStreamSource, which encapsulates any class that can return InputStream, such as File, resources under Classpath, Byte, Array, etc. It defines only one method: InputStream getInputStream () throws IOException;, which returns an InputStream object.

The Resource interface abstracts all the underlying resources used within Spring: File, URL, Classpath, and so on. The methods in the Resource API and their general functions are shown below:

(Resource interface)

There are Resource implementations of objects for resource files from different sources:

Files (FileSystemResource), Classpath resources (ClassPathResource), URL resources (UrlResource), etc.

(some related classes for resource file processing)

The loading of resource files is also often used in daily development. You can directly use the classes provided by Spring, such as the following code when loading files:

Resource resource = new ClassPathResource ("resource file")

InputStream inputStream = resource.getInputStream ()

Once we have inputStream, we can develop in the same way as before, and we can also use something about Resource and its implementation classes.

When the encapsulation of the configuration file is completed through Resource related classes, the reading of the configuration file is completed by XmlBeanDefinitionReader.

Now that we know that the configuration file is encapsulated as a Resource object in Spring, let's move on to the initialization process of XmlBeanFactory. From the above XmlBeanFactory class structure diagram, you can see that the XMLBeanFactory class has two constructors, as shown in the following figure:

(XmlBeanFactory class constructor)

As we can see from the figure above, another constructor within the class is called inside the first constructor. So, we also understand the second construction method.

First, super (parentBeanFactory) appears on the first line, calling a constructor of the parent class (DefaultListableBeanFactory).

(DefaultListableBeanFactory has parameter construction method)

When we come to the parent class constructor, we find that we continue to call the parent class (AbstractAutowireCapableBeanFactory) constructor, as shown in the following figure:

(AbstractAutowireCapableBeanFactory class constructor)

As you can see from the figure, the parametric construction method (what we use is the parametric construction) first calls a non-parametric construction method in this class, and the no-parameter construction method first executes the construction method of the parent class (AbstractBeanFactory) (an empty method). Here, take a look at the ignoreDependencyInterface method, the main function of this method is to ignore the automatic connection of the given dependent interface (ignoring the automatic assembly function of the given interface). So, what's the use of this method?

For example, when there is attribute B in class A, when Spring obtains the Bean of A, if attribute B has not been initialized, Spring will initialize B automatically (this is also an important feature of Spring). However, in some cases, B will not be initialized, such as when B implements the BeanNameAware interface. Introduction to Spring API: it is often used by application contexts to register dependencies that are resolved in other ways, such as BeanFactory implemented through BeanFactoryAware or ApplicationContext implemented through ApplicationContextAware. By default, only the BeanFactoryAware interface is ignored. To ignore other types, call this method for each type.

Finally, the setParentBeanFactory method is called to set the BeanFactory object.

(setParentBeanFactory method)

In the setParentBeanFactory method, there is an if judgment that determines whether the BeanFactory has been associated, and throws an exception if it is already associated.

? Load Bean

When we talk about Resource above, we know the constructor of XmlBeanFactory, and we also know that one of the constructors first calls the constructor of the parent class, so under the super () statement is the call to the this.reader.loadBeanDefinitions (resource) method. This method is the entry point for the entire resource load, and the following is the timing diagram of the method call:

(loadBeanDefinitions method execution sequence diagram)

As you can see from the figure above, the call to this method causes a lot of work. However, this work is just preparatory work, so let's talk about what is being prepared here:

(1) encapsulate resource files. When the loadBeanDefinitions method is called, it jumps to that method, which invokes an overloaded method of the class and creates an EncodedResource object as a parameter based on the Resource object. The purpose of using EncodedResource is to encapsulate Resource using the EncodedResource class.

(loadBeanDefinitions (Resource resource) method)

(2) get the input stream to build inputSource. Get the corresponding InputStream from Resource and create an InputSource.

(get InputStream and create InputSource in the loadBeanDefinitions (EncodedResource encodedResource) method)

(3) continue to call the doLoadBeanDefinitions () method through the InputSource object and Resource you just created.

(doLoadBeanDefinitions (InputSource, Resource) method call)

Above, we have seen EncodedResource many times, so what on earth is it?

? EncodedResource

You can guess from the name that this class is related to coding. This class mainly deals with the coding of resource files. One of the most important methods, the getReader () method, when the encoding property is set, Spring uses the corresponding encoding as the encoding of the input stream.

First take a look at one of its constructors: (there are four constructors for this class, but the other three constructors all call the following)

(a constructor of the EncodedResource class)

The main purpose of this constructor is to initialize the properties in the class.

Let's look at the getReader () method:

(getReader () method)

The getReader () method constructs an InputStreamReader with encoding. After encapsulating Resource as an EncodedResource object, you come to the loadBeanDefinitions () method in the XmlBeanDefinitionReader class (another overloaded method), which is the method in the following figure.

(loadBeanDefinitions (EncodedResource.) Method part of the important code)

The above method is the real data preparation, that is, the part described in the seventh sequence diagram up.

Reviewing the above data preparation part again, first encapsulate the incoming Resource object as EncodedResource, why do you need to encapsulate it? The purpose is to consider that there may be coding requirements in Resource. Secondly, the InputSource object is prepared by reading the XML file by SAX, and finally the prepared data is passed through parameters to the core processing method doLoadBeanDefinitions (InputSource inputSource, Resource resource). Let's see what the doLoadBeanDefinitions () method does:

(doLoadBeanDefinitions () method part code (except catch part))

There are multiple catch behind the doLoadBeanDefinitions () method try, and apart from these catch, this code does three things:

(1) get the verification mode for XML files

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

(3) register Bean information according to the returned Document object

The above three operations support the implementation foundation of the entire Spring container, so let's start with these three steps.

? Get the authentication mode of XML

The role of XML verification mode: to ensure the correctness of XML files (seemingly the so-called constraints), there are two commonly used verification modes: DTD (Document Type Definition) and XSD (XML Schemas Definition). For more information about the verification mode, please search the Internet by yourself.

In the previous (doLoadBeanDefinitions method code) figure, we saw that the first line of code in the try block is: Document document = doLoadDocument (inputSource, resource); the doLoadDocument () method in this class is called, but this code is mainly used to get the Document object, which is the second thing above; however, the acquisition of the validation mode of the XML file will be completed first.

(doLoadDocument () method)

As we can see from the figure above, when the loadDocument () method executes, the getValidationModeForResource (resource) method is executed first, which returns a value of type int. (in Spring3.2, there is no doLoadDocument () method, instead of calling the getValidationModeForResource (resource) method and the loadDocument () method directly in the doLoadBeanDefintions () method, let's take a look at what the getValidationModeForResource (resource) method does:

(getValidationModeForResource (resource) method)

In the above method, several constants are used, and the following figure shows the values represented by several constants:

(several constants in the org.springframework.util.xml.XmlValidationModeDetector class)

Note: the XmlBeanDefinitionsReader class also has several constants of the same name of the int type other than the DOCTYPE constant in the above figure, and their values are the values above. That is, Spring uses different numerical values to represent different validation modes.

In the second picture above, we know that the getValidationModeForResource (resource) method first determines whether the verification mode is manually specified (the verification mode is set by the setValidationMode () method). The way of judgment is to get the validationMode attribute to judge. Otherwise, automatic detection is used to call the org.springframework.beans.factory.xml.XmlBeanDefinitionReader.detectValidationMode (resource) method (the method in this class).

(the XmlBeanDefinitionReader.detectValidationMode (resource) method omits part of the code for catch processing)

In the last try block in the above figure, the detectValidationMode (inputStream) method in the XmlValidationModeDetector class is called for further processing. Let's take a look at this method (here, if you want a comprehensive understanding, you are advised to take a look at the source code. After all, other methods are called and several constants are used in this method, which are not listed here).

(detectValidationMode (inputStream) method in the XmlValidationModeDetector class)

The above part of getting the validation pattern needs to be understood according to DTD and XSD, because the acquisition of the validation pattern is based on the use of the two validation modes. The way Spring detects the validation mode is to determine whether it contains DOCTYPE, if it is DTD, otherwise it is XSD (as you can see from the first line of comment in the previous figure: check the file to find DOCTYPE), which can be easily seen in the method above.

At this point, getting the validation mode is over.

? Get Document

We know above that you need to get the XML authentication mode before you get the Document. Let's take a look at how to get Document in Spring. In the above (doLoadDocument () method) figure, we see that the doLoadDocument method calls the loadDocuemnt () method of this class documentLoader. DocumentLoader is defined as follows:

Private DocumentLoader documentLoader = new DefaultDocumentLoader ()

DocumentLoader is an interface, so use it to implement the class DefaultDocumentLoader

Let's take a look at the loadDocument () method in the DefaultDocumentLoader class.

(loadDocument () method)

The above code is the basic parsing of XML through SAX, which is a basic step. First create the DocumentBuilderFacotry object, then create the DocumentBuilder through DocumentBuilderFactory, and then parse the inputSource to return the Document object. Here involves the relevant knowledge of XML analysis, you can access the Internet in-depth understanding.

? Parsing and registering BeanDefinitions

In the above (doLoadBeanDefinitions () method) figure, we know that after we get the Document, we execute the following line of code:

Return registerBeanDefinitions (doc, resource)

That is, continue to call the registerBeanDefinitions (doc, resource) method.

(registerBeanDefinitions (doc, resource) method)

The first line of code in the figure above is to create that BeanDefinitionDocumentReader,BeanDefinitionDocumentReader is an interface, and instantiation is done in the createBeanDefinitionDocumentReader () method, and after executing this method, the real type of BeanDefinitionDocumentReader is DefaultBeanDefinitionDocumentReader (its implementation class).

The third line in the figure above is to load and register Bean. Since BeanDefinitionDocumentReader is the interface, we come to the registerBeanDefinitions () method in the DefaultBeanDefinitionDocumentReader class.

(registerBeanDefinitions (Document, XmlReaderContext) method)

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

(doRegisterBeanDefinitions (Element) method)

The profile attribute is involved in the code in the above figure. For more information, please go online. In the second part of the program above, the program will first get whether the beans node defines the profile attribute. If so, it needs to look in the middle area of the environment variable, and each definition is not parsed.

After processing the profile, you can start reading the XML. Let's take a look at the method parseBeanDefinitions (root, this.delegate) framed above.

(parseBeanDefinitions (Element, BeanDefinitionParserDelegate) method)

You can use the default Bean declaration in the XML file of Spring, or you can customize it. So Spring handles different Bean statements differently.

At this point, I believe you have a deeper understanding of "how to use Spring container BeanFactory". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report