Simple Analysis of bean construction process in Spring IoC container

Source: Internet
Author: User

Spring construction bean and Management initialization life cycle are processed in abstractautowirecapablebeanfactory, which can be divided into construction bean and subsequent management bean initialization life cycle.

1. Construct Bean

1.1 method call Diagram

The entry to construct the bean is the getbean () method of beanfactory. Actually, the getbean () method of defaultbeanfactory is called. Wait until aw.actautowirecapablebeanfactory. The call method is shown as follows:

3-6 are all completed in abstractautowirecapablebeanfactory.

1.2 design class diagram

The class graph inheritance relationships involved are as follows:

In docreatebean (), createbeaninstance returns a beanwrapper

Beanwrapper provides the ability to set and obtain attribute values (single or batch), obtain attribute description information, query read-only or writable attributes, and use getwrappedinstance () method to obtain the encapsulated bean instance. The object in beanwrapperimpl is the beanwrapper "wrapped" bean, which is provided externally through the getwrappedinstance () method.

1.3 Method Analysis

This section mainly analyzes the methods in abstractautowirecapablebeanfactory. Methods in other classes are encapsulated in this method.

Get a, beanwrapper

Beanwrapper provides the ability to set and obtain attribute values (single or batch), obtain attribute description information, query read-only or writable attributes, and use getwrappedinstance () method to obtain the encapsulated bean instance. The object in beanwrapperimpl is the beanwrapper "wrapped" bean, which is provided externally through the getwrappedinstance () method.

/**      * Return the bean instance wrapped by this object, if any.      * @return the bean instance, or <code>null</code> if none set      */      Object getWrappedInstance();

Beanwrapper is obtained by createbeaninstance. Call createbeaninstance () in docreatebean () and return beanwrapper.

if (instanceWrapper == null) {                 instanceWrapper = createBeanInstance(beanName, mbd, args);           }

B. createbeaninstance () Implementation Analysis

Beanwrapper is obtained in createbeaninstance (). This method calls instantiatebean (). The instantiatebean () method declaration is as follows:

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) ;

The code for obtaining beanwrapper in createbeaninstance () is as follows:

Beaninstance = getinstantiationstrategy (). instantiate (mbd, beanname, parent); // construct the required response BW = new beanwrapperimpl (beaninstance); // put this bean into the corresponding beanwrapper

Getinstantiationstrategy () returns cglibsubclassinginstantiationstrategy, because during the initialization of abstractautowirecapablebeanfactory

private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

Therefore, by default, spring uses the cglib library to construct bean objects, rather than reflection in JDK.

C. instantiate () Implementation

The instantiate () method in cglibsubclassinginstantiationstrategy is as follows:

public Object instantiate(Constructor ctor, Object[] args) {                 Enhancer enhancer = new Enhancer();      enhancer.setSuperclass(this.beanDefinition.getBeanClass());                 enhancer.setCallbackFilter(new CallbackFilterImpl());                 enhancer.setCallbacks(new Callback[] {                            NoOp.INSTANCE,                            new LookupOverrideMethodInterceptor(),                            new ReplaceOverrideMethodInterceptor()                 });                 return (ctor == null) ?                             enhancer.create() :                             enhancer.create(ctor.getParameterTypes(), args);           }

Here we call the cglib library to construct an object, which is also a standard call to construct an object using the cglib library.

2. Follow-up work

In the future, bean lifecycle management will be completed.

Spring lifecycle Overview 1

1) set the property value;

2) Call the beannameaware. setbeanname () method in bean. If the bean implements the beannameaware interface;

3) Call the beanfactoryaware. setbeanfactory () method in bean. If this bean implements the beanfactoryaware interface;

4) Call beanpostprocessors. postprocessbeforeinitialization;

5) Call the afterpropertiesset method in bean. If the bean implements the initializingbean interface;

6) Call the init-method in bean. The init-method is usually specified when bean is configured. For example:<Beanclass = "beanclass" init-method = "init"> </bean>

7) Call beanpostprocessors. postprocessafterinitialization;

8) If the bean is a singleton bean, The destory method is called when the container is destroyed and the bean implements the disposablebean interface. If the bean is prototype, then, the prepared bean is submitted to the caller, and the bean lifecycle will not be managed in the future.

The initializebean () method corresponds to 2-7 of the bean lifecycle in abstractautowirecapablebeanfactory. Initializebean () is called after createbeaninstance () in docreatebean. Four methods are called:

Invokeawaremethods (corresponding to Lifecycle 2 and 3)

Applybeanpostprocessorsbeforeinitialization (corresponding to Lifecycle 4)

Invokeinitmethods (corresponding to Lifecycle 5, 6)

Applybeanpostprocessorsafterinitialization (corresponding to Lifecycle 7)

2.1 invokeawaremethods:

Invokeawaremethods calls three methods of bean introspection (if this bean implements the beannameaware interface, beanclassloaderaware interface, beanfactoryaware Interface)

private void invokeAwareMethods(final String beanName, final Object bean) {           if (bean instanceof Aware) {                 if (bean instanceof BeanNameAware) {                      ((BeanNameAware) bean).setBeanName(beanName);                 }                 if (bean instanceof BeanClassLoaderAware) {                      ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());                 }                 if (bean instanceof BeanFactoryAware) {                      ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);                 }           }      }

2.2 applybeanpostprocessorsbeforeinitialization

To complete the pre-processing, call the postprocessbeforeinitialization () method to complete specific requirements before bean initialization.

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)                 throws BeansException {           Object result = existingBean;           for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {                 result = beanProcessor.postProcessBeforeInitialization(result, beanName);                 if (result == null) {                      return result;                 }           }           return result;      }

2.3 invokeinitmethods

Call the afterpropertiesset () method. If init-method is specified during bean configuration, call invokecustominitmethod.

Boolean isinitializingbean = (bean instanceof initializingbean );...... (Initializingbean) bean). afterpropertiesset (); // call afterpropertiesset () method invokecustominitmethod (); // call the specified init-Method

2.4 applybeanpostprocessorsafterinitialization

Similar to postprocessbeforeinitialization, the post-processing after Bean Initialization is completed. In the for loop of postprocessbeforeinitialization (), change:

Result = beanprocessor. postprocessafterinitialization (result, beanname );

3. Others


It seems that the implementation of spring's bean construction and bean object lifecycle management is easier and easier to understand than the initialization process of Spring IoC container.

4. References

1. http://sexycoding.iteye.com/blog/1046775:about the lifecycle of spring Bean

2. Refer to Chapter 2 of spring technology insider-in-depth analysis of spring architecture and design principles

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.