Spring internal working mechanism (I): spring Internal Working Mechanism

Source: Internet
Author: User

Spring internal working mechanism (I): spring Internal Working Mechanism

Spring has many internal mechanisms, so I plan to write them in several more stages.

This chapter only explores what Spring container startup has done;

Preface:

It is said that Spring containers are like a well-constructed machine. This is true. We use the configuration file to send control information to the machine so that the machine can work in the set mode.

If we compare Spring containers to a car, we can regard BeanFactory as the engine of the car, while ApplicationContext is the whole car. It includes not only the engine, but also the clutch, transmission, and chassis, body, electrical equipment and other components, in ApplicationContext, each component step by step to complete the functions of the car.

Body:

Spring's AbstractApplicationContext is the abstract implementation class of ApplicationContext. The refresh () method of this abstract class defines the processing processes of Spring containers after loading the configuration file, which is very clear.

Let's take a look at the execution logic defined in this method.

@ Override public void refresh () throws BeansException, IllegalStateException {synchronized (this. startupShutdownMonitor) {// Prepare this context for refreshing. prepareRefresh (); // ① initialize BeanFactory catalog ablelistablebeanfactory beanFactory = obtainFreshBeanFactory (); // Prepare the bean factory for use in this context. prepareBeanFactory (beanFactory); try {// Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory (beanFactory); // ② call the factory post-processor worker (beanFactory); // ③ register the Bean post-processor registerBeanPostProcessors (beanFactory); // ④ initialize the initMessageSource (); // ⑤ initialize the application context event broadcaster initApplicationEventMulticaster (); // ⑥ initialize other special beans and implement onRefresh () by sub-classes; // 7 register the event listener registerListeners (); // producer initializes all the beans of a single instance. Except for beans in the lazy loading mode, finisjavasanfactoryinitialization (beanFactory); // producer completes the refresh and releases the container refresh event finishRefresh ();} catch (BeansException ex) {// slightly} finally {// Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches ();}}}

There are nine main processing operations. The following describes these operations in detail.

(1) initialize BeanFactory: instantiate BeanFactory according to the configuration file. In the obtainFreshBeanFactory () method, call the refreshBeanFactory () method to refresh BeanFactory, and then call the getBeanFactory () method to obtain BeanFactory,

Both methods are implemented by specific sub-classes. In this step, Spring loads the configuration file information into the BeanDefinitionRegistry of the container, but the Bean has not yet been initialized.

The source code of the obtainFreshBeanFactory () method is attached as follows:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {        refreshBeanFactory();        ConfigurableListableBeanFactory beanFactory = getBeanFactory();        if (logger.isDebugEnabled()) {            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);        }        return beanFactory;    }

(2) Call the factory postprocessor: Find all beans that implement the BeanFactoryPostProcessor interface from BeanDefinitionRegistry Based on the reflection mechanism, and call its postProcessBeanFactory () interface method. Some source code is also attached.

if (beanFactory instanceof BeanDefinitionRegistry) {            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;            List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();            List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =                    new LinkedList<BeanDefinitionRegistryPostProcessor>();            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {                    BeanDefinitionRegistryPostProcessor registryPostProcessor =                            (BeanDefinitionRegistryPostProcessor) postProcessor;                    registryPostProcessor.postProcessBeanDefinitionRegistry(registry);                    registryPostProcessors.add(registryPostProcessor);                }                else {                    regularPostProcessors.add(postProcessor);                }            }

(3) Register Bean post-processor: Find all beans that implement the BeanPostProcessor interface from BeanDefinitionRegistry Based on the reflection mechanism, and register them in the registry of the container Bean post-processor.

(4) initialize the message source: Initialize the international message resources of the container. Presumably this is better understood.

(5) initialize the application context event broadcaster.

(6) initialize other special beans: This is a hook method. Subclass can use this method to perform some special operations, such as AbstractRefreshableWebApplicationContext.

(7) register the event listener.

(8) Initialize all single-instance beans, except for beans in the lazy loading mode: After initializing beans, put them into the cache pool of the Spring container. (Add one sentence: If this single-instance Bean with the "lazy loading" sign is referenced by a non-lazy loading single-instance Bean, the lazy loading fails)

(9) publish a context refresh event: create a context refresh event. The event broadcaster broadcasts the events to each registered event listener. (The Event content is described in the following sections)

 

The next section describes the Spring container job flow from loading the configuration file to creating a complete Bean and the involved roles.

Related Article

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.