spring source code analysis Series 5: ApplicationContext is initialized with the Bean Life Cycle

Bean review of relations with BeanDefinition. BeanFactory container. ApplicationContext context.

First summarize:

    Bean developer defines information: divided into XML format defined; annotation defined by the formula

    Bean ApplicationContext defined collection; storing the BeabFactory container.

    Bean BeanFactory create these BeanDefinition. Cached for our use.

[Developers] – labeled -> [Bean define] — collection -> [BeanDefinition] — create -> [Bean]

This section: We analyzed this process from the code level.


refresh () method describes the initialization process ApplicationContext, a process that most of the work to define the process BeanDefinition execution Bean to the Bean.

refresh () term can be roughly divided into five parts:

1.BeanDefinition storage before preparation phase:

    prepareRefresh () initialization ;: The main environmental attributes, check.

    obtainFreshBeanFactory () ;: prepare a beanFactory () (Note: XML configuration form Bean mostly performed at this time collecting storage)

    prepareBeanFactory (beanFactory) ;: beanFactory configuration information, including loading the class; the class loader, resolver, and needs to be ignored depends dependent early Bean class processor, to create environment-related Bean

    postProcessBeanFactory (beanFactory); as long as the method for increasing the correlation properties of the web type configuration beanFactory context.

The total for this stage was doing the configuration beanFactory.

2.BeanDefinition collection storage phases:

    invokeBeanFactoryPostProcessors (beanFactory): This method is primarily a collection of annotation type BeanDefinition, register these BeanDefinition, execution BeanFactoryPostProcessor.postProcessBeanFactory () method, modify the operation of storage do.

This process is very subtle. () Responsible for all of PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors,
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors () method essentially would have done two things:

    Perform the registration type BeanFactoryPostProcessor: At this point there is an important ConfigurationClassPostProcessor registrar, such a configuration would annotation type BeanDefinition find and register to the BeanFactory.

    The implementation of a common type of BeanFactoryPostProcessor: make changes to the operation of storage.

3. Some special features of the Bean created in advance:
    This stage of the small number of special use to create BeanDefinition Bean for use.

    registerBeanPostProcessors (beanFactory); preparing instantiation of some BeanPostProcessor generate Bean for future BeanDefinition. .

    initMessageSource (); initialization ApplicationContext international related components Bean, message bindings, message parsing

    initApplicationEventMulticaster () ;: initialization broadcast component Bean, for broadcast during initialization stage event.

    OnRefresh (); subclass special initialization Beans (can be considered an extension point)

    registerListeners () ;: the container listener Bean, provided to the broadcaster to go.

4. Common Bean generation stage BeanDefinition
    This stage is the most BeanDefinition generated Bean stage.

  • finishBeanFactoryInitialization (beanFactory) ;:
                This process is the article said, applicationContext the context of the internal trigger BeanDefinition beanFactory create Bean.

    We imagine a scenario: a first machine to feed the first into the BeanDefinition, then press start switch for producing .ApplicationContext here like the start switch is pressed producing Bean, Bean production process is a pipeline, the pipeline. there are different types of machines for raw material processed differently to finally obtain Bean

ApplicationContext call DefaultListableBeanFactory.preInstantiateSingletons () began to trigger the creation of Bean:


    First check whether this warehouse Bean has been created, there are taken out

    Not ready to take the pipeline to create Bean created.

    Create a check before the material there? There are, currently marked in the creation of Bean

    Check for dependence, yes, go to create a load-dependent Bean. Back to the 1

    Analyzing scope, the createBean () pipeline ready for execution.


    Bean load the Class class

    Preparation and verification methods to be covered

doGetBean-> createBean-> proxy object: return proxies

    Create a proxy object: to BeanPostProcessors a chance to return a proxy object instead of real examples (to return here for custom TargetSource of Bean)

doGetBean-> createBean-> doCreateBean: do not create a custom proxy object continues

    Suitable examples strategy used to create Bean (factory method, constructor automatic injection, a simple initialization), and the objects obtained BeanWrapper Bean wrapper class.

    Call BeanDefinitionPostProcessor postprocessor, modify BeanDefinition

    Resolve circular dependencies Singleton pattern: the solution is exposed Bean as soon as possible references to the cache, so that other objects can be referenced to him

    Setting bean properties populateBean

  1. initializeBean:

doGetBean-> createBean-> doCreateBean-> initializeBean Bean instantiated

    invokeAwareMethods: _awre type of execution method

    applyBeanPostProcessorsBeforeInitialization the implementation of the pre-method BeanPostProcessor

    invokeInitMethods: performing InitializingBean interface afterPropertiesSet, invokeCustomInitMethod perform customized init-method method

    applyBeanPostProcessorsAfterInitialization: after methods of performing BeanPostProcessor

    Bean returned. At this point BeanDefinition to Bean production process is complete.

5.applicationContext finishing stage

  • finishRefresh ();
                In fact, the final stage is also considered the extension point applicationContext. Lifecycle interface Lifecycle interfaces,

    (1. First will get from Bean container LifecycleProcessor type of Bean, if not then create a default DefaultLifecycleProcessor.LifecycleProcessor is doing with? LifecycleProcessor is used to process the bean Lifecycle interfaces.

    (2. obtain LifecycleProcessor execution of the Lifecycle interface implements Bean’s start () method

    (3. Publish the context of the completion of the initialization event

    (4.Participate in LiveBeansView MBean, if active. Why are not very clear.

Bean’s life cycle

After reading the refresh () method. Let us summarize Bean life cycle.


Bean’s complete life cycle is divided into four phases:

  1. The first stage: instantiating stage.
                Bean definition storage order from the execution collected BeanDefinition
                BeanDefinitionRegistryPostProcessor registration processor register some BeanDefinition
                BeanFactoryPostProcessor, for storage BeanDefinition be modified definition.
                BeanWrapper generation, BeanWrapper is an early product of Bean.
                populateBean () set execution attributes
                Summary: This stage is set BeanDefinition-> BeanWrapper, various properties

  2. Second stage: initialization phase: mainly perform various initialization methods
                invokeAwareMethods (beanName, bean); Aware execution attribute settings.
                BeanPostProcessor.postProcessBeforeInitialization pre-execution method,
                If you implement InitializingBean.afterPropertiesSet () This method is executed
                InitMethod execute custom method.
                The method of performing a post BeanPostProcessor.postProcessBeforeInitialization,

  3. The third stage: the use phase
                Bean getBean removed from the buffer vessel

  4. Phase IV: the destruction stage
                DisposableBean.distroy execution method
                Perform a custom detry-method

to sum up:

The entire spring initialization process can be seen as

    Material (BeanDefinition) collection storage (BeanFactory)

    Line (the getBean ()) material removed to create the finished product (Bean)

    Finished (Bean) storage (BeanFactory)


Leave a Reply