Interpretation of SPRING-IOC source code 2-Container initialization process

Source: Internet
Author: User

1. IOC Container initialization process: the initialization of the IOC container is initiated by the refresh () method, which includes: Beandifinition's resource positioning, loading and registering three processes. The initialization process does not include implementations of bean dependency injection.

    • The first process is the positioning process of the resource. The positioning of this resource refers to the Beandefinition resource location, which is accomplished by resourceloader through a unified resource interface.
    • The second process is beandefinition loading, which represents the user-defined bean as the container's internal data structure (i.e., beandefinition)
    • The third process is the process of registering these beandefinition with the IOC container.

2. below we take classpathxmlapplicationcontext as an example to analyze the implementation of this applicationcontext, using the spring version is version 3.0.2. First look at the code and configuration file we tested:

    • Definition of 2.1:javabean
public class Person {private String name;private int age;private int sex;private Dog dog;private list<address> addre Sslist;
}public class Dog {private String dogname;} public class Address {private string type;private string city;}
    • 2.2beans.xml file Definition:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns=    "Http://www.springframework.org/schema/beans" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!--Person object--><bean id=" Person " class= "Com.pepper.spring.model.Person" ><property name= "name" value= "Pepper"/><property name= "age" Value= "/><property name=" Sex "value=" 1 "/><property name=" dog "ref=" dog "/><property name=" AddressList "><list><ref bean=" Home "/><ref bean=" work "/></list></property></ bean><!--the Dog property of the person object--><bean id= "dog" class= "Com.pepper.spring.model.Dog" ><property name= " Dogname "value=" Edward "/></bean><!--the two values of the Person object AddressList property--><bean id=" Home "class=" Com.pepper.spring.model.Address "><property name=" type "value=" Home "/><property name=" CITY "value=" SX "/></bean><bean id=" work "class=" com.pepper.spring.model.Address "><property name=" Type "value=" work "/><property name=" City "value=" SZ "/></bean></beans>
    • 2.3. Container Startup class:
public class Testspring {public static final String bean_config_file = "e:/workspace_selflearn/read-spring/src/ Spring-beans.xml ";p ublic static final String Bean_config_class =" Spring-beans.xml ";p ublic static void Main (string[] args) {testapplicationcontext ();} Use xmlbeanfactorypublic static void Testbeanfactory () {Resource res = new Classpathresource (bean_config_class); Beanfactory FAC = new Xmlbeanfactory (res); Person p = fac.getbean ("person", person.class); SYSTEM.OUT.PRINTLN (P);}        Use applicationcontextpublic static void Testapplicationcontext () {ApplicationContext ac = null;     AC = new Filesystemxmlapplicationcontext (bean_config_file), ac = new Classpathxmlapplicationcontext (BEAN_CONFIG_ CLASS); Person p = ac.getbean ("person", person.class); SYSTEM.OUT.PRINTLN (P);}}

3. Let's look at the definition of the Classpathxmlapplicationcontext class first:

public class Classpathxmlapplicationcontext extends Abstractxmlapplicationcontext {private resource[] Configresources    ;        Public Classpathxmlapplicationcontext () {} public Classpathxmlapplicationcontext (ApplicationContext parent) {    Super (parent); }//Configlocation object indicates the file path beandefinition is located on public classpathxmlapplicationcontext (String configlocation) throws Bea    NSException {This (new string[] {configlocation}, true, NULL); }//Spring supports incoming multiple beandefinition profiles public classpathxmlapplicationcontext (String ... configlocations) throws Beansexc    eption {This (configlocations, true, null); This construction method, in addition to the configuration file path, allows you to specify the parent IOC container public classpathxmlapplicationcontext (string[] configlocations that you want to use, Applicationco    ntext parent) throws Beansexception {This (Configlocations, true, parent); } public Classpathxmlapplicationcontext (string[] configlocations, Boolean refresh) throws Beansexception {This ( Configlocations, refresh, null);    }//During initialization of the object, call the Refresh () method to start the beandefinition loading process public classpathxmlapplicationcontext (string[] configlocations,        Boolean refresh, ApplicationContext parent) throws Beansexception {super (parent);        Setconfiglocations (configlocations);        if (refresh) {refresh (); }} public Classpathxmlapplicationcontext (string[] paths, Class clazz) throws Beansexception {This (paths, CL    Azz, NULL);         } public Classpathxmlapplicationcontext (string[] paths, Class Clazz, ApplicationContext parent) throws Beansexception {        Super (parent);        Assert.notnull (Paths, "Path array must not is null");        Assert.notnull (Clazz, "Class argument must not being null");        This.configresources = new Resource[paths.length];        for (int i = 0; i < paths.length; i++) {this.configresources[i] = new Classpathresource (Paths[i], clazz);    } refresh (); }//This is the resource implementation applied to the CLASSPATH, and this getresource is in the Beandefinitionreader class (AbstRactxmlapplicationcontext) is called in the Loadbeandefinition method of the 
Loadbeandefinition adopts the template method design pattern, the concrete implementation is actually by each sub-class to realize. @Override protected resource[] Getconfigresources () {return this.configresources; }}

When the container starts, it calls the constructor of the Classpathxmlapplicationcontext, and the Refresh () method is called in this constructor, which is very important, an interface that is critical to our analysis of the container initialization process. The input, parsing, and registration of the bean that we analyzed later begins with this method.

public void Refresh () throws Beansexception, IllegalStateException {synchronized (this.startupshutdownmonitor) {            Prepare this contextual for refreshing. Prepare context Preparerefresh (); Tell the subclass to refresh the internal bean factory. Notifies the subclass to refresh the internal bean factory Configurablelistablebeanfactory beanf            Actory = Obtainfreshbeanfactory (); Prepare The Bean Factory for use            Context. Prepare beanfactory to use this context. Do some preparatory work, such as Classloader,beanfactorypostprocessor preparebeanfactory (beanfactory); try {//allows post-processing of the Bean factory in context subclasses. Allows beanfactory to be performed in a subclass context                Post-processing postprocessbeanfactory (beanfactory); Invoke factory processors registered as beans in the context. Call the factory processor as a bean to register in the context INVOKEBEANFACTORYPOSTP                Rocessors (beanfactory);    Register bean processors that intercept bean creation. Start registering beanpostprocessor to intercept the bean creation process            Registerbeanpostprocessors (beanfactory);                Initialize the message source for the this context. Initializes the Initmessagesource.                Initialize Event Multicaster for this context. Events broadcast Initapplicationeventmulticaster ();                Initialize other special beans in specific context subclasses. Initializes a special bean Onrefresh () in the context of a specific subclass;                Check for listener beans and register them. Examine the listener bean and register registerlisteners (); Instantiate all remaining (Non-lazy-init) singletons. Instantiate all of the remaining singleton beans Finishbeanfactoryinitiali                Zation (beanfactory);            Last Step:publish corresponding event. The final step, release the Application Finishrefresh ();                 } catch (Beansexception ex) {//Destroy already created singletons to avoid dangling resources.                Destroybeans ();                Reset ' active ' flag.CancelRefresh (ex);                Propagate exception to caller.            Throw ex; }        }    }

  

Interpretation of SPRING-IOC source code 2-Container initialization process

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.