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 summarize and Design the IOC Container in Spring

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to carry out the overview and design of the IOC container in Spring. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. Spring IoC Container Overview 1.1.Why should IoC containers and dependency inversion patterns rely on reversals?

When the dependency is reversed, the acquisition of the dependent object is actually reversed.

If the reference or dependency management of cooperative objects is completed by specific objects, it will lead to high coupling and reduced testability of the code. In object-oriented systems, objects encapsulate data and deal with data, and the dependency of objects often depends on data and methods, so handing the dependency injection of objects to the framework and IoC container can improve the testability of code while decoupling.

Implementation of dependency inversion in Spring

In Spring, IoC container is the carrier of dependency inversion, which allows objects to directly inject data into objects when they are generated or initialized, and to inject dependencies on method calls by injecting references to objects into the object data domain. This dependency injection can recursively inject objects layer by layer.

By using the IoC container, the management of object dependencies is reversed and transferred to the IoC container. The interdependencies between objects are managed by the IoC container, and the object injection is completed by the IoC container.

2. Design and implementation of IoC Container Series 2.1 Ioc Container Series BeanFactory and ApplicationContext

In the design of Spring IoC containers, we can see two main container families. One is a simple container family that implements the BeanFactory interface, which only implements the basic functions of the container.

The other is the ApplicationContext application context, which exists as an advanced form of the container. On the basis of simple containers, it adds a lot of framework-oriented features and adapts to the application environment.

2.2 Design of Spring IoC container

The main interface design diagram of the IoC container is shown below:

As can be seen from the above figure, there are two design routes for IoC container interfaces:

From the interface BeanFactory to HierarchicalBeanFactory, and then to ConfigableBeanFactory is a major design route.

The other is the interface design route with the ApplicationContext application context interface as the core. From BeanFactory to ListableBeanFactory and HierarchicalBeanFactory, then to ApplicationContext, and then to commonly used WebApplicationContext or ConfigableApplicationContext.

The green part of the picture is a partial abstract class and interface implementation class, which will not be studied for the time being.

For the first interface design route, BeanFactory defines the basic container design specification. After inheriting the basic BeanFactory interface, HierarchicalBeanFactory adds the getParentBeanFactory () interface function, which makes BeanFactory have the management function of parent IoC container. The later ConfigableBeanFactory mainly defines some configuration features of BeanFactory (such as setting up a parent IoC container through setParentBeanFacory (), etc.). The basic functionality of the BeanFactory simple IoC container is defined by the superposition of these functions.

For the second interface design route, ListableBeanFactory and HierarchicalBeanFactory are the interfaces connecting BeanFactory and ApplicationContext; many functions of the BeanFactory interface are refined in the ListableBeanFactory interface, and the getParentBeanFactory () interface function is added to the HierarchicalBeanFactory interface, so that BeanFactory has the management function of the parent IoC container; for the ApplicationContext interface, by inheriting interfaces such as ResourcePatternResolver,ApplicationEventPublisher,MessageSource, many advanced container features are supported on the basis of BeanFactory simple container.

2.3 BeanFactory interface public interface BeanFactory {String FACTORY_BEAN_PREFIX = "&"; / / if you start with &, get the FactoryBean itself; otherwise, get the instance created by FactoryBean. / / get Bean Object getBean (String name) throws BeansException;// can be alias T getBean (String name, Class requiredType) throws BeansException; Object getBean (String name, Object...) Args) throws BeansException; T getBean (Class requiredType) throws BeansException; T getBean (Class requiredType, Object...) Args) throws BeansException; / / to determine whether it contains bean. Whether it is an abstract class, lazy loading, or not within the scope of the container, true is returned as long as it conforms to it. Therefore, when returning true, you may not be able to obtain instance boolean containsBean (String name) from getBean; / / judgment of singleton, prototype, bean type boolean isSingleton (String name) throws NoSuchBeanDefinitionException; boolean isPrototype (String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch (String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException; boolean isTypeMatch (String name, Class typeToMatch) throws NoSuchBeanDefinitionException;//, alias Class getType (String name) throws NoSuchBeanDefinitionException Design principle of String [] getAliases (String name);} 2.4 BeanFactory container

Take XmlBeanFactory as an example to illustrate the design principle of simple IoC container BeanFactory.

2.4.1 XmlBeanFactory class inheritance relationship

You can see that XmlBeanFactory inherits from DefaultListableBeanFactory and actually uses DefaultListableBeanFactory as a full-featured IoC container in Spring.

2.4.2 implementation of XmlBeanFactory public class XmlBeanFactory extends DefaultListableBeanFactory {private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader (this); public XmlBeanFactory (Resource resource) throws BeansException {this (resource, null);} public XmlBeanFactory (Resource resource, BeanFactory parentBeanFactory) throws BeansException {super (parentBeanFactory); this.reader.loadBeanDefinitions (resource);}}

As you can see from the name of XmlBeanFactory, it is an IoC container that can read BeanDefinition defined as a XML file.

A XmlBeanDefinitionReader object is initialized in XmlBeanFactory to handle BeanDefinition defined as an XML file.

When constructing XmlBeanFactory, the IoC container, you need to specify the source of XML information, which needs to be encapsulated into a Resource class of Spring.

Resource is constructed from the location of the xml file, and then Resource is passed into the constructor of XmlBeanFactory. In this way, the IoC container can locate the required BeanDefinition information to complete the container initialization and dependency injection process.

2.4.3 summarize the steps for using the IoC container

Referring to the implementation of XmlBeanFactory, we summarize it programmatically using DefaultListableBeanFactory.

Public void mytest () {ClassPathResource resource = new ClassPathResource ("applicationContext.xml"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory (); XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader (factory); System.out.println (beanDefinitionReader.loadBeanDefinitions (resource)); Person p = (Person) factory.getBean ("personChild"); System.out.println (p);}

The following steps are required to discover the reuse of the IoC container:

Create an abstract resource for the IoC container that defines the definition information for the BeanDefinition.

Create a BeanFactory. This is DefaultListableBeanFactory.

Create a reader for BeanDefinition and configure it to BeanFactory through a callback. This is XmlBeanDefinitionReader.

The configuration information is read from the defined resource location, and the specific parsing process is completed by XmlBeanDefinitionReader. Once you have finished loading and registering the Bean definition, you can use the IoC container.

2.5 ApplicationContext interface

The interface relationship of ApplicationContext: as shown in the following figure.

It can be seen that ApplicationContext adds a lot of additional functions to BeanFactory and provides a lot of new and new features for ApplicationContext, so ApplicationContext is an IoC container with advanced morphological meaning in BeanFactory.

2.6Design principle of ApplicationContext container

In ApplicationContext in BeanFactory container, take the implementation of FileSystemXMLApplicationContext as an example to illustrate the design principle of ApplicationContext in BeanFactory container.

The source code for FileSystemXMLApplicationContext is as follows:

Public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {public FileSystemXmlApplicationContext (String [] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {super (parent); setConfigLocations (configLocations); / / this refresh operation involves a series of operations initiated by the IoC container. Operations are similar for different containers, so they are encapsulated in the base class. If (refresh) {refresh ();} @ Override protected Resource getResourceByPath (String path) {if (path! = null & & path.startsWith ("/")) {path = path.substring (1);} return new FileSystemResource (path);}}

You can see from the code that the main functions have been implemented in the base class AbstractXmlApplicationContext, and only two functions related to your own design are needed in FileSystemXmlApplicationContext.

Function one

Support for instantiating the application context when the application uses the FileSystemXmlApplicationContext container directly, and initiating the refresh function of the IoC container.

Function two

Different container implementations correspond to different BeanDefinition read implementations, and the read BeanDefinition implementation in FileSystemXmlApplicationContext is shown in the above code.

This is the end of the overview and design of the IOC container in Spring. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

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

Internet Technology

Wechat

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

12
Report