The life cycle of beans in Spring

Source: Internet
Author: User
Tags aop prepare stub

Spring has been warmly welcomed by programmers as the most popular and powerful lightweight framework in current Java. It is essential to understand the life cycle of the spring bean accurately. We usually use ApplicationContext as the spring container. Here, we are also talking about the life cycle of the bean in ApplicationContext. In fact, Beanfactory is similar, but the processor needs to register manually.

Reprint Please specify address http://www.cnblogs.com/zrtqsk/p/3735273.html, thank you.

One, life cycle flow chart:

The full lifecycle of the spring Bean begins with the creation of the spring container until the final spring container destroys the bean, which contains a series of key points.


 

If the container registers the above various interfaces, the procedure then will proceed according to the above process. The interface functions will be carefully explained below. second, the specific source code 2.1:

ApplicationContext factory = new Classpathxmlapplicationcontext ("Com/spring/beanlife/beans.xml");//Create Bean Context
Source code: Public
classpathxmlapplicationcontext (String configlocation) throws Beansexception {This
		(new string[] { Configlocation}, True, null);
	}
Public Classpathxmlapplicationcontext (string[] configlocations, Boolean refresh, ApplicationContext parent)
			Throws Beansexception {

		super (parent);
		Setconfiglocations (configlocations);
		if (refresh) {
			refresh ();//Specific in this method
		}
	}
public void Refresh () throws Beansexception, IllegalStateException {
		synchronized (this.startupshutdownmonitor) {
			//Prepare this context for refreshing.
			Preparerefresh ();

			Tell the subclass to refresh the internal bean factory.
			Configurablelistablebeanfactory beanfactory = Obtainfreshbeanfactory ();//Create beanfactory, and load
                        Beandefintion info

			//Prepare The Bean Factory for use in this context.
			Preparebeanfactory (beanfactory)//Prepare beanfactory

			try {
				//allows post-processing of the Bean factory in context Subclasses.
				Postprocessbeanfactory (beanfactory);

				Invoke factory processors registered as beans in the context.
                               Triggers the beanfactorypostprocessor, instantiates the beanfactorypostprocessor, and executes the Postprocessbeanfactory method
Invokebeanfactorypostprocessors (beanfactory);//Register bean processors that intercept bean creation.
                                Instantiation of Beanpostprocessor and Instantiationawarebeanpostprocessor
				registerbeanpostprocessors (beanFactory);

				The Initialize message source is for the context.
				Initmessagesource ();

				Initialize Event Multicaster for the this context.
				Initapplicationeventmulticaster ();

				Initialize other special beans in the specific context subclasses.
				Onrefresh ();

				Check for listener beans and register them.
				Registerlisteners ();

				Instantiate all remaining (Non-lazy-init) singletons.
				Finishbeanfactoryinitialization (beanfactory);

				Last Step:publish corresponding event.
				Finishrefresh ();
			}

			catch (Beansexception ex) {
				//Destroy already created singletons to avoid dangling.
				Destroybeans ();

				Reset ' active ' flag.
				CancelRefresh (ex);

				Propagate exception to caller.
				Throw ex;}}}
	


II. classification of various interface methods

The full lifecycle of a bean undergoes various method invocations, which can be divided into the following categories:

1, the Bean's own method: This includes the method that the bean itself invokes and the method specified by the Init-method and Destroy-method of the <bean> in the configuration file

2. Bean-Level Lifecycle interface method: This includes methods for Beannameaware, Beanfactoryaware, Initializingbean, and Diposablebean these interfaces

3, container-level life Cycle interface method: This includes the instantiationawarebeanpostprocessor and beanpostprocessor these two interface implementations, generally called their implementation class is "post processor."

4, factory after the interface method: This includes Aspectjweavingenabler, Configurationclasspostprocessor, customautowireconfigurer, etc. very useful in the factory after the processor The method of the interface. The factory post processor is also container-level. Called immediately after the context assembly configuration file is applied.

The 5:spring aware interfaces are:

Beannameaware, you can then get the instance name of the bean in the IOC container in the bean

Beanfactoryaware,applicationcontextaware,messagesourceaware,applicationeventpublisheraware,resourceloaderawate

  

Third, demonstration

We use a simple spring bean to demonstrate the life cycle of the spring bean.

1. The first is a simple spring Bean that invokes the Bean's own method and the bean-level lifecycle interface method, which, for the sake of demonstration, implements Beannameaware, Beanfactoryaware, Initializingbean and Diposablebean These 4 interfaces, with 2 methods, corresponding to <bean> Init-method and Destroy-method in the configuration file. As follows:

Package com.spring.beanlife;
Import org.springframework.beans.BeansException;
Import Org.springframework.beans.factory.BeanFactory;
Import Org.springframework.beans.factory.BeanFactoryAware;
Import Org.springframework.beans.factory.BeanNameAware;
Import Org.springframework.beans.factory.DisposableBean;

 Import Org.springframework.beans.factory.InitializingBean; /** @author QSK */public class person implements Beanfactoryaware, Beannameaware, Initializingbean, Di
     Sposablebean {private String name;
     Private String address;
 
     private int phone;
	public static Beanfactory Getbeanfactory () {return beanfactory;
     private static Beanfactory beanfactory;
 
     Private String Beanname;
     Public person () {System.out.println (the person constructor invokes the constructor instantiation of person);
     Public String GetName () {return name;
         public void SetName (String name) {System.out.println (' person ' injects attribute ' injected attribute name '); This.nAME = name;
     Public String getaddress () {return address;
         public void setaddress (String address) {System.out.println (the "person" injection attribute "inject property address");
     this.address = address;
     public int Getphone () {return phone;
         public void Setphone (int phone) {System.out.println (the "Person" injection property "inject property phone");
     This.phone = phone; @Override public String toString () {return ' person [address= ' + address +], name= "+ name +", ph
     One= "+ Phone +"]; //This is the Beanfactoryaware interface method @Override public void Setbeanfactory (Beanfactory arg0) throws Beansexception
         {System.out. println ("person" Beanfactoryaware Interface "Invoke Beanfactoryaware.setbeanfactory ()");
     This.beanfactory = arg0; }//This is the Beannameaware interface method @Override public void Setbeanname (String arg0) {System.out.println ("Pe Rson "BeannameAware interface "Call Beannameaware.setbeanname ()");
     This.beanname = arg0; //This is the Initializingbean interface method @Override public void Afterpropertiesset () throws Exception {System
     . Out. println (the "person" Initializingbean Interface "invokes Initializingbean.afterpropertiesset ()"); }//This is the Diposiblebean interface method @Override public void Destroy () throws Exception {System.out.println ("
     Person "Diposiblebean Interface" calls Diposiblebean.destory ()); ///The initialization method specified by the <bean> Init-method property is public void Myinit () {System.out.println () ' Person ' Init-met
     Hod "invokes the initialization method specified by the Init-method property of <bean>"); ///The initialization method specified by the <bean> Destroy-method property is public void Mydestory () {System.out.println ()
     Stroy-method "invokes the initialization method specified by the Destroy-method property of <bean>");
 }
}


2, Next is the demonstration Beanpostprocessor interface method, as follows:

Package com.spring.beanlife;


Import org.springframework.beans.BeansException;
Import Org.springframework.beans.factory.config.BeanPostProcessor;

public class Mybeanpostprocessor implements Beanpostprocessor {public

    mybeanpostprocessor () {
        super ();
         System.out.println ("This is the Beanpostprocessor implementation class Builder ..."). ");
         TODO auto-generated constructor stub
     }
 
     @Override Public
     object Postprocessafterinitialization (object arg0, String arg1)
             throws beansexception {
         System.out
         . println (" Beanpostprocessor interface method Postprocessafterinitialization make changes to properties. ");
         return arg0;
     }
 
     @Override Public
     Object Postprocessbeforeinitialization (Object arg0, String arg1)
             throws Beansexception {
         System.out
         . println ("Beanpostprocessor interface method postprocessbeforeinitialization to make changes to properties." ");
         Return arg0
     }
 }


As above, the Beanpostprocessor interface consists of 2 methods Postprocessafterinitialization and Postprocessbeforeinitialization, The first parameter of both methods is the Bean object to be processed, and the second parameter is the name of the bean. The return value is also the Bean object to be processed. Here to note.

3, the Instantiationawarebeanpostprocessor interface is essentially a beanpostprocessor sub-interface, In general we inherit the adapter class Instantiationawarebeanpostprocessor adapter provided by spring to use it, as follows:

Package com.spring.beanlife;

Import Java.beans.PropertyDescriptor;
Import org.springframework.beans.BeansException;
Import org.springframework.beans.PropertyValues;

Import Org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; public class Myinstantiationawarebeanpostprocessor extends Instantiationawarebeanpostprocessoradapter {PU
         Blic Myinstantiationawarebeanpostprocessor () {super (); System.out. println ("This is the Instantiationawarebeanpostprocessoradapter implementation class Builder.
     ");
             }//interface method, @Override public Object postprocessbeforeinstantiation (Class beanclass) is called before instantiating the bean. String beanname) throws Beansexception {System.out. println ("Instantiationawarebeanpostproces
         Sor call postprocessbeforeinstantiation method ");
     return null; }//interface method, instantiated bean @Override public Object Postprocessafterinitialization (object bean, String beanname
         )    Throws Beansexception {System.out. println ("Instantiationawarebeanpostprocessor Call Postproces
         Safterinitialization method ");
     return bean;
             //interface method, set a property call @Override public propertyvalues postprocesspropertyvalues (propertyvalues PVs,
                 Propertydescriptor[] PDS, Object Bean, String beanname) throws Beansexception {System.out
         . println ("Instantiationawarebeanpostprocessor call Postprocesspropertyvalues method");
     return PVS; }
 }

There are 3 ways to do this, and the second method, Postprocessafterinitialization, is to rewrite the Beanpostprocessor method. The third method, Postprocesspropertyvalues, is used to manipulate the property, and the return value should also be the Propertyvalues object.

4, demo factory after the processor interface method, as follows:

Package com.spring.beanlife;
 Import org.springframework.beans.BeansException;
 Import org.springframework.beans.factory.config.BeanDefinition;
 Import Org.springframework.beans.factory.config.BeanFactoryPostProcessor;

 Import Org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
         public class Mybeanfactorypostprocessor implements Beanfactorypostprocessor {public mybeanfactorypostprocessor () {
         Super (); System.out.println ("This is the Beanfactorypostprocessor implementation class Builder ...").
     "); @Override public void Postprocessbeanfactory (Configurablelistablebeanfactory arg0) throws Beans
        Exception {System.out. println ("Beanfactorypostprocessor invoke Postprocessbeanfactory method"); Arg0.getbean ("person"); the//getbean method is to get the bean that has been initialized successfully, where the bean has not yet been initialized, so calling this method will cause an error beandefinition BD = arg0.getbe
         Andefinition ("person");
     Bd.getpropertyvalues (). Addpropertyvalue ("Phone", "110"); }
 
 }


5, the configuration file as follows Beans.xml, very simple, use ApplicationContext, the processor does not need to register manually:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:aop= " Http://www.springframework.org/schema/aop "xmlns:tx=" Http://www.springframework.org/schema/tx "xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schem A/beans/spring-beans-3.2.xsd "> <bean id=" beanpostprocessor "class=" Com.spring.beanlife.MyBeanPostProcessor " > </bean> <bean id= "instantiationawarebeanpostprocessor" class= "Com.spring.beanlife.MyInstantiationA Warebeanpostprocessor "> </bean> <bean id=" beanfactorypostprocessor "class=" Com.spring.beanlife.MyBean Factorypostprocessor "> </bean> <bean id =" Myapplicationcontextaware "lazy-init=" true "class=" Com.spri
    Ng.beanlife.MyApplicationContextAware "></bean><bean id= "Person" class= "Com.spring.beanlife.Person" lazy-init= "true" init-method= "Myinit" destroy-method= "Myde" Story "scope=" Singleton "P:name=" John "p:address=" Guangzhou "p:phone=" 15900000000 "/> <!--<bean id=" friend "C lass= "Com.spring.beanlife.Friend" lazy-init= "true" init-method= "Myinit" destroy-method= "Mydestory" scope= "Singleto" n "p:name=" Dick "p:address=" Shenzhen "p:phone=" 1666666 "/>--> </beans>


6:myapplicationcontextaware

Package com.spring.beanlife;

Import org.springframework.beans.BeansException;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.ApplicationContextAware;

public class Myapplicationcontextaware implements applicationcontextaware{

	private static ApplicationContext ApplicationContext = null;
	@Override public
	void Setapplicationcontext (ApplicationContext applicationcontext)
			throws Beansexception {
		//TODO auto-generated method stub
		System.out.println ("-------------set ApplicationContext");
		This.applicationcontext = ApplicationContext;
	}

	public static ApplicationContext Getapplicationcontext () {return
		applicationcontext;
	}
}


6, the following test:

Import Org.springframework.beans.factory.BeanFactory;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
         
		         public class Application {public static void main (string[] args) {System.out.println ("Start the container Now");
		          ApplicationContext factory = new Classpathxmlapplicationcontext ("Com/spring/beanlife/beans.xml"); 
		          System.out.println ("Successful container initialization");
		          ApplicationContext ApplicationContext = Myapplicationcontextaware.getapplicationcontext ();
		          Get Preson, and use Factory.getbean ("Myapplicationcontextaware");
		          Person person = Factory.getbean ("person", person.class);
		          /*beanfactory Factory2 = Person.getbeanfactory ();
		          
		          Person person = Factory2.getbean ("person", person.class); *///system.out.println (person); System.out.println ("Now start closing the container.")
		          "); ((Classpathxmlapplicationcontext) factory). regIstershutdownhook ();
 }

}

The container is closed using a abstractapplicationcontext hook method.

Let's take a look at the results:

This is the Beanfactorypostprocessor implementation class Builder.
Beanfactorypostprocessor Call Postprocessbeanfactory method
This is the Beanpostprocessor implementation class Builder.
This is the Instantiationawarebeanpostprocessoradapter implementation class Builder.
container initialization succeeds
in//myapplicationcontextaware The bean initialization, and if you increase lazy-init= "true" in the configuration, you can view Method Abstractapplicationcontext.finishbeanfactoryinitialization (beanfactory);

Instantiationawarebeanpostprocessor Call Postprocessbeforeinstantiation Method
Instantiationawarebeanpostprocessor Call the Postprocesspropertyvalues method
-------------Set ApplicationContext
Beanpostprocessor interface method Postprocessbeforeinitialization make changes to properties.
Beanpostprocessor interface Method Postprocessafterinitialization make changes to properties.
Instantiationawarebeanpostprocessor Call postprocessafterinitialization method
Instantiationawarebeanpostprocessor
to invoke the constructor instantiation
of person by calling the Postprocessbeforeinstantiation method person constructor Instantiationawarebeanpostprocessor calls the Postprocesspropertyvalues method person
"inject attribute" to inject property address person
"inject attribute" Inject property name Person
"Inject attribute" inject property phone person
"Beannameaware interface" calls Beannameaware.setbeanname () person
" Beanfactoryaware interface "Call Beanfactoryaware.setbeanfactory ()
Beanpostprocessor interface method Postprocessbeforeinitialization make changes to properties. Person
"Initializingbean interface" calls Initializingbean.afterpropertiesset ()
The initialization method
specified by the person "Init-method" Call <bean> Init-method Property Beanpostprocessor interface method Postprocessafterinitialization make changes to properties.
Instantiationawarebeanpostprocessor calls the Postprocessafterinitialization method
now starts closing the container.


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.