In-depth analysis of Spring IOC container creation process

Source: Internet
Author: User

Preface

The creation process of Spring IOC container is researched and analyzed based on its source code. It mainly involves the creation process of BeanFactory and Bean parsing and registration process, bean instantiation process and IOC construction process such as ClassPathXmlApplicationContext.

IOC container creation process

In Spring, Context combines Bean and Core in the Context, Bean, and Core components, so that the three Core components interact with each other to build the foundation of Spring. In Spring, the refresh () of AbstractApplicationContext, a subclass of ApplicationContext, is the entry point for Bean construction. It sets the template method for IOC creation. When you create an IOC Sub-class, the sub-class will be delegated to this method for creation.

Refresh () source code of AbstractApplicationContext:

Public void refresh () throws BeansException, IllegalStateException {synchronized (this. startupShutdownMonitor) {// prepare the context to refresh prepareRefresh (); // create BeanFactory, parse Bean definitions and register javasablelistablebeanfactory beanFactory = obtainFreshBeanFactory (); // configure the generated BeanFactory prepareBeanFactory (beanFactory) for the context; try {// you can call the custom BeanFactory to modify the generated BeanFactory postProcessBeanFactory (beanFactory ); invokeBeanFactoryPostProcessors (beanFactory); // you can add some custom operations to create Bean instance objects later. registerBeanPostProcessors (beanFactory); // initialize the information source initMessageSource (); // initialization event initApplicationEventMulticaster (); // other special Bean onRefresh (); registerListeners () in a specific context; // The Real instantiation of Bean, create a non-Lazy Singleton Bean finishBeanFactoryInitialization (beanFactory); finishRefresh ();} catch (BeansException ex) {destroyBeans (); cancelRefresh (ex); throw ex ;}}


The whole method code uses the template-based design mode and factory-based method mode to define the entire BeanFactory build process. Construct BeanFactory to generate the desired Bean object, register events that may be of interest, create Bean instance objects, and trigger the event to be listened on. The IOC container is the Bean network formed by combining the Context and the other two core components. It is a large Bean container.

In the process of parsing the IOC container creation, the following two lines of code are prototype, interspersed with the creation process of parsing the IOC. This is a common IOC container creation process. IOC is created only through a new ClassPathXmlApplicationContext.

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService service = ctx.getBean("ser",UserService.class);

The inheritance relationship of ClassPathXmlApplicationContext is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112Q33505-0.jpg "title =" ioc .jpg "/>

When we create a new ClassPathXmlApplicationContext and pass it the address of a bean configuration file, the final called constructor is as follows:

Public ClassPathXmlApplicationContext (String [] configLocations, boolean refresh, ApplicationContext parent) {super (parent); // set the configLocations setConfigLocations (configLocations); if (refresh) {// The refresh of the parent class AbstractApplicationContext is called here // It is also confirmed that refresh is the entry point for IOC construction refresh ();}}

From the source code, we can see that the first sentence will eventually call the AbstractApplicationContext constructor in the inheritance relationship. The specific task is to return a PathMatchingResourcePatternResolver.

Second, set the location of the configuration file, call the method of the parent class AbstractRefreshableConfigApplicationContext, and set the value of configLocations. If you create a constructor using this constructor and do not set the value of configResources, the value is null. (This section describes how to create an IOC instance ).

In the third sentence, the constructor calls the refresh method of the parent class AbstractApplicationContext to create the IOC.

BeanFactory creation:

BeanFactory creation is completed in the obtainFreshBeanFactory method. In this method, the Child class is called to implement the refreshBeanFactory method and refresh the Child class. If the BeanFactory exists, the Child class is refreshed. If the child class does not exist, a new BeanFactory is created. The default BeanFactory is created by DefaultListableBeanFactory.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112Q3L44-1.jpg "title =" beanfactorytime sequence. jpg "/>


This is a sequence chart created by BeanFactory. It contains the BeanFactory creation process, the Bean definition parsing, loading, and registration process, and the Bean definition parsing and loading registration process, the detailed sequence diagram is described below. The refresh () method calls refreshBeanFactory () to construct the standard initialization process of BeanFactory. The BeanFactory of ClassPathXmlApplicationContext follows this construction process.

Bean parsing registration process:

In the above sequence diagram, the rightmost side shows loading, parsing, and registering Bean definitions,

LoadBeanDefinitions is called in AbstractXmlApplicationContext. In this case, XmlBeanDefinitionReader is used to load the specified bean definition. The loadBeanDefinitions () method source code of the AbstractXmlApplicationContext class is as follows:

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {        Resource[] configResources = getConfigResources();        if (configResources != null) {            reader.loadBeanDefinitions(configResources);        }        String[] configLocations = getConfigLocations();        if (configLocations != null) {            reader.loadBeanDefinitions(configLocations);        }    }

This method loads our Bean definitions based on the specified XmlBeanDefinitionReader, and performs resolution and registration processing.

Here, we generally only execute one of the if Statements. Here, we use ClassPathXmlApplicationContext. As mentioned earlier, the new process only sets the configLocations value and does not set the configResources attribute value, then the second if statement is executed directly. Here, the loadBeanDefinitions method of AbstractBeanDefinitionReader is called, and the loadBeanDefinitions () method of XmlBeanDefinitionReader is called ()

The specific standard Bean parsing registration process is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112Q342C-2.jpg "title =" bean registration sequence. jpg "/>


Other initialization and preparation processes:

After BeanFactory is created, the Bean we define is only parsed and registered. In fact, they have not actually created their instance objects. After the obtainFreshBeanFactory () method is returned, the BeanFactory that has just been generated is configured for the context. To expand the IOC container of Spring, then you can perform custom operations in the following three code parts:

postProcessBeanFactory(beanFactory);invokeBeanFactoryPostProcessors(beanFactory);registerBeanPostProcessors(beanFactory);

When a BeanFactory is created, we can call a custom BeanFactory to modify the created configuration. The last sentence is that some custom operations can be defined in the Bean instantiation process.

The next step is to initialize the context information source, application events, and other special beans.


Bean Instance Object creation process:

In the refresh, finishBeanFactoryInitialization is called to complete the Bean Instance Object creation process. The sequence of Bean creation is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112Q330W-3.jpg "title =" beancreate sequence. jpg "/>

In the Bean creation process, there is a special FactoryBean. This is a special Bean. It is a factory Bean that can produce Bean beans. The Bean generated here refers to the Bean instance, if a class inherits FactoryBean, you can define the method to generate the instance object as long as its getObject method is implemented. In Spring, the instance object of this Bean is FactoryBean. by calling the getObject method of this object, you can obtain the user-defined objects, which provides good scalability for Spring. Spring adds & to get the FactoryBean object.


In the second line of our sample code, when getBean is used, the process is as follows:

1, it will call the abstract method getBeanFactory ()

2. Finally, call the getBeanFactory of AbstractRefreshableApplicationContext, which is the final method.


This article from the "dream in the cloud" blog, please be sure to keep this source http://computerdragon.blog.51cto.com/6235984/1244016

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.