Spring IOC Container Source analysis-the rest of the initialization work

Source: Internet
Author: User
Tags creative commons attribution throwable

1. Introduction

This article is the last article in the "Spring IOC container Source Analysis" series, the object of this article is the Initializebean method, which is used to perform the final initialization of the bean that is populated with the completed attribute. Compared to the previous articles in the analysis of the source code, Initializebean source is relatively simple, we can enjoy reading. Well, the rest is not much to say, let's go straight into the subject.

2. Source Code Analysis

In this chapter we will analyze the source code of the Initializebean method. After the analysis is completed, the execution flow of the method is listed as usual. Well, look at the source bar:

protectedObjectInitializebean(FinalString Beanname,FinalObject Bean, rootbeandefinition mbd) {if(System.getSecurityManager() !=NULL) {Accesscontroller.doprivileged(NewPrivilegedaction<object> () {@Override             PublicObjectRun() {Invokeawaremethods(Beanname, Bean);return NULL; }        },Getaccesscontrolcontext()); }Else{//If the Bean implements Beannameaware, Beanfactoryaware, Beanclassloaderaware and other interfaces, it injects related objects into the bean        Invokeawaremethods(Beanname, Bean); } Object Wrappedbean = bean;if(mbd = =NULL|| !MBD.issynthetic()) {//Perform bean initialization pre-operationWrappedbean =applybeanpostprocessorsbeforeinitialization(Wrappedbean, Beanname); }Try{/** Call initialization method:* 1. If the bean implements the Initializingbean interface, call the Afterpropertiesset method* 2. If the user has configured the Bean's Init-method property, call the method specified in the configuration by the user         */        Invokeinitmethods(Beanname, Wrappedbean, mbd); }Catch(Throwable ex) {Throw New beancreationexception((mbd! =NULL? mbd.getresourcedescription() :NULL), Beanname,"Invocation of Init method failed", ex); }if(mbd = =NULL|| !MBD.issynthetic()) {//Perform bean initialization post-operation, where AOP will weave the facet logic into the target objectWrappedbean =applybeanpostprocessorsafterinitialization(Wrappedbean, Beanname); }returnWrappedbean;}

The above is the logic of the Initializebean method, very simple is not. The method does a few things like this:

    1. Detects if the bean implements the *aware type interface and, if implemented, injects the appropriate object into the bean
    2. Perform bean initialization pre-operation
    3. Perform an initialization operation
    4. Perform a bean initialization post-operation

In the process above, we found traces of the back processor. If you read the source code of spring, you will find that the post-processor in the spring source code has appeared many times. The post processor is one of the Spring extension points, and by implementing the Post processor Beanpostprocessor interface, we can intervene in the bean initialization process. For example, the familiar AOP is in the post-processing Postprocessafterinitialization method to the target object is woven as the tangent logic. About the "pre-processing" and "post-processing" of the relevant source code, here is not analyzed, we are interested to see their own. Next analyze the Invokeawaremethods and Invokeinitmethods methods, as follows:

Private void Invokeawaremethods(FinalString Beanname,FinalObject Bean) {if(BeaninstanceofAware) {if(BeaninstanceofBeannameaware) {//Inject Beanname string((Beannameaware) bean).Setbeanname(Beanname); }if(BeaninstanceofBeanclassloaderaware) {//Inject ClassLoader object((Beanclassloaderaware) bean).Setbeanclassloader(Getbeanclassloader()); }if(BeaninstanceofBeanfactoryaware) {//Inject Beanfactory object((Beanfactoryaware) bean).setbeanfactory(Abstractautowirecapablebeanfactory. This); }    }}

The logic of the Invokeawaremethods method is simple, and one sentence is summed up: injecting different types of objects into the bean based on the type of Aware the Bean implements.

protected void Invokeinitmethods(String Beanname,FinalObject Bean, rootbeandefinition mbd)throwsThrowable {//detects if the bean is of type Initializingbean    BooleanIsinitializingbean = (beaninstanceofInitializingbean);if(Isinitializingbean && (mbd = =NULL|| !MBD.Isexternallymanagedinitmethod("Afterpropertiesset"))) {if(Logger.isdebugenabled()) {logger.Debug("Invoking Afterpropertiesset () on Bean with Name '"+ Beanname +"'"); }if(System.getSecurityManager() !=NULL) {Try{Accesscontroller.doprivileged(NewPrivilegedexceptionaction<object> () {@Override                     PublicObjectRun()throwsException {((Initializingbean) bean).Afterpropertiesset();return NULL; }                },Getaccesscontrolcontext()); }Catch(Privilegedactionexception PAE) {ThrowPae.getexception(); }        }Else{//If the Bean implements Initializingbean, the Afterpropertiesset method is called to execute the initialization logic((Initializingbean) bean).Afterpropertiesset(); }    }if(mbd! =NULL) {String initmethodname = mbd.Getinitmethodname();if(Initmethodname! =NULL&&! (Isinitializingbean &&"Afterpropertiesset".equals(Initmethodname)) &&!MBD.Isexternallymanagedinitmethod(Initmethodname)) {//Call user-defined initialization method            Invokecustominitmethod(Beanname, Bean, mbd); }    }}

The Invokeinitmethods method is used to execute the initialization method, and it is not complicated to say much.

3. Summary

This article is almost analyzed here, in general, the content of this article is relatively simple, it is easy to read. This article is the last article in my "Spring IOC container Source Analysis" series, as described in the introduction chapter. After writing this article, there is a sense of relief. I wrote the Java CAS principle Analysis article on May 15, the next day began to read the Spring IOC part of the source code, read this part of the source code took about two weeks time. Then on May 30 released the "Spring IOC container Source analysis" series of articles in the first article of the Spring IOC container source Analysis series of articles guide. After writing the first article, the fast update mode is turned on, with an average of 2 days to update the speed of an article. Finally in today, that is, June 11 wrote the last article. This period of time to write articles written very tired, often stay up late. The main reason is that, in their own understanding of the source code at the same time, through the way to write the article as far as possible to ensure that others can read, this is more difficult. For example, when I read the source code, I wrote some simple comments on the source code. These comments I can understand, but if you want to write an article, you need to put the comments in as much detail as possible, necessary background knowledge to introduce. In general, it is not easy to write a technical article carefully. Writing an article is still so, it must be more difficult to write books. In the process of reading the source code and writing the article, I also refer to some information (relevant information in the "Guide" article indicated the source, this article does not explain again). Here, thank you to the author of this material!

Well, this article is here, thank you for reading.

This article is published under the Knowledge Sharing License Agreement 4.0, the reprint must indicate the source in the obvious position
Coolblog.xyz
This document is posted in my personal blog: http://www.coolblog.xyz


This work is licensed under the Creative Commons Attribution-NonCommercial use-no derivative of the 4.0 International License Agreement.

Spring IOC Container Source analysis-the rest of the initialization work

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.