The life cycle of Spring beans

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/zrtqsk/p/3735273.html

As the most popular and powerful lightweight framework in Java, Spring is warmly welcomed by programmers. It is necessary to have an accurate understanding of the spring Bean's life cycle. We usually use ApplicationContext as the spring container. Here, we are talking about the life cycle of the bean in ApplicationContext. In fact, Beanfactory is similar, but the processor needs to be manually registered.

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

First, life cycle flowchart:

The full life cycle of the spring bean starts 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 registered the above various interfaces, the program will follow the above process. The interface functions are explained in detail below.

II. classification of various interface methods

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

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

2. Bean-level life-Cycle interface method: This includes Beannameaware, Beanfactoryaware, Initializingbean, and Diposablebean these interface methods

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

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

  

Third, the demonstration

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

1, the first is a simple spring bean, the method of invoking the bean itself and the bean-level life-cycle interface method, in order to facilitate the demonstration, it realizes the Beannameaware, Beanfactoryaware, Initializingbean and Diposablebean are 4 interfaces, and there are 2 methods that correspond to the Init-method and Destroy-method of <bean> in the configuration file. As follows:

 1 package springbeantest; 2 3 Import org.springframework.beans.BeansException; 4 Import org.springframework.beans.factory.BeanFactory; 5 Import Org.springframework.beans.factory.BeanFactoryAware; 6 Import Org.springframework.beans.factory.BeanNameAware; 7 Import Org.springframework.beans.factory.DisposableBean; 8 Import Org.springframework.beans.factory.InitializingBean; 9/**11 * @author qsk12 */13 public class person implements Beanfactoryaware, beannameaware,14 Initializingbe  An, Disposablebean {name;17 private string address;18 private int phone;19 Private Beanfactory beanfactory;21 Private String beanname;22 the public person () {System.out.println ("constructor" calls P Erson constructor instantiation ");}26 public String getName () {name;29}30 to public void SetName (STR ing name) {System.out.println ("injection attribute" injection attribute name "); this.name = name;34}35-Public String get Address () {37        Return address;38}39-public void setaddress (String address) {SYSTEM.OUT.PRINTLN ("injection Attribute" injection property      Address "), this.address = address;43}44, public int getphone () {49 return phone;47}48     public void Setphone (int phone) {System.out.println ("inject attribute" injection property "); This.phone = phone;52  }53 @Override55 public String toString () {* * * return ' person [address= + address + ', name= "+ name + ", phone=" + Phone + "]"; 58}59 60//This is the Beanfactoryaware interface method @Override62 public void Setbeanfactory (Beanfactory arg0) throws Beansexception {System.out64. println ("" Beanfactoryawar     E Interface "Call Beanfactoryaware.setbeanfactory ()"); this.beanfactory = arg0;66}67 68//This is the Beannameaware interface method 69 @Override70 public void Setbeanname (String arg0) {System.out.println ("Beannameaware interface" Call beannameaware.se        Tbeanname () "); 72 This.beanname = arg0;73}74 75//This is the Initializingbean interface method @Override77 public void Afterpropertiesset () t Hrows Exception {system.out79. println ("Initializingbean interface" Call Initializingbean.afterpropertiess ET () "); 80}81 82//This is the Diposiblebean interface method @Override84 public void Destroy () throws Exception {S YSTEM.OUT.PRINTLN ("Diposiblebean Interface" calls Diposiblebean.destory () "), 86}87 88//initialization method specified by the Init-method property of <bean> 8 9 public void Myinit () {System.out.println ("" Init-method "call <bean> the Init-method attribute of the specified initialization method"); 91}92 93//94 public void Mydestory () {System.out.println ("" destroy-m) by the initialization method specified by the Destroy-method property of <bean> Ethod "Call <bean> the Destroy-method property of the specified initialization method"); 96}97}

2, next is to demonstrate the Beanpostprocessor interface method, as follows:

 1 package springbeantest; 2 3 import org.springframework.beans.BeansException; 4 import Org.springframework.beans. Factory.config.BeanPostProcessor; 5 6 public class Mybeanpostprocessor implements Beanpostprocessor {7 8 public mybeanpostprocessor () {9 sup ER (); System.out.println ("This is the Beanpostprocessor implementation class constructor!! ")//TODO auto-generated constructor stub12}13 @Override15 public Object Postprocessafteriniti Alization (Object arg0, String arg1) throws Beansexception {system.out18. println ("Beanpos Tprocessor interface Method Postprocessafterinitialization Change the properties! ARG0;20}21 @Override23 public Object Postprocessbeforeinitialization (object arg0, STR ing arg1) throws beansexception {system.out26. println ("Beanpostprocessor interface method POSTPROCESSB Eforeinitialization make changes to Properties! "); arg0;28}29} 

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 bean's name. The return value is also the Bean object to be processed. Be careful here.

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

 1 package springbeantest; 2 3 Import Java.beans.PropertyDescriptor; 4 5 Import Org.springframework.beans.BeansException; 6 Import org.springframework.beans.PropertyValues; 7 Import Org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; 8 9 public class Myinstantiationawarebeanpostprocessor Extends10 Instantiationawarebeanpostprocessoradapter {11 1 2 public Myinstantiationawarebeanpostprocessor () {a super (); system.out15 println ( "This is the Instantiationawarebeanpostprocessoradapter implementation class Builder!!" "); 16}17 18//interface method, instantiate bean before calling @Override20 public Object postprocessbeforeinstantiation (Class Beanclas s,21 String beanname) throws Beansexception {system.out23. println ("Instantiationaw     Arebeanpostprocessor call Postprocessbeforeinstantiation Method "), return null;25}26 27//interface method, call 28 after instantiating the bean @Override29 public Object postprocessafterinitialization (objecT Bean, String beanname) throws Beansexception {System.out32. println ("Instantiat      Ionawarebeanpostprocessor call Postprocessafterinitialization Method "), return bean;34}35 36//interface method, call 37 when setting a property @Override38 public propertyvalues postprocesspropertyvalues (propertyvalues pvs,39 propertydescriptor[ ] PDS, Object Bean, String beanname)-throws Beansexception {system.out42. println ("Instantiationawarebeanpostprocessor call Postprocesspropertyvalues method"); return pvs;44}45}

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 be the Propertyvalues object.

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

1 package springbeantest; 2  3 import org.springframework.beans.BeansException; 4 Import Org.springframework.beans.factory.config.BeanDefinition; 5 Import Org.springframework.beans.factory.config.BeanFactoryPostProcessor; 6 Import Org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 7  8 public class Mybeanfactorypostprocessor implements Beanfactorypostprocessor {9     Mybeanfactorypostprocessor () {         one super ();         System.out.println ("This is the Beanfactorypostprocessor implementation class Builder!! ");     }14 @Override16 public     void Postprocessbeanfactory (configurablelistablebeanfactory arg0) 17             throws beansexception {         system.out19                 . println (" Beanfactorypostprocessor call Postprocessbeanfactory method ");         beandefinition bd = arg0.getbeandefinition (" person ") ;         bd.getpropertyvalues (). Addpropertyvalue ("Phone", "}23");     24}

5, the configuration file is as follows Beans.xml, very simple, uses the ApplicationContext, the processor does not have the manual registration:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" 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/schema/    Beans/spring-beans-3.2.xsd "> <bean id=" beanpostprocessor "class=" Springbeantest.mybeanpostprocessor "> </bean> <bean id= "Instantiationawarebeanpostprocessor" class= " Springbeantest.myinstantiationawarebeanpostprocessor "> </bean> <bean id=" Beanfactorypostprocessor " class= "Springbeantest.mybeanfactorypostprocessor" > </bean> <bean id= "person" class= "SPRINGBEANTEST.P Erson "init-method=" Myinit "destroy-method=" Mydestory "scope=" Singleton "P:name=" Zhang San "p:address=" Guangzhou "P:phoNe= "15900000000"/></beans> 

6, the following test:

1 package springbeantest; 2  3 import org.springframework.context.ApplicationContext; 4 Import Org.springframework.context.support.ClassPathXmlApplicationContext; 5  6 public class Beanlifecycle {7  8 public     static void Main (string[] args) {9         System.out.println ("Now open         ApplicationContext factory = new Classpathxmlapplicationcontext ("Springbeantest/beans.xml"). ;         System.out.println ("success of container Initialization");    +         //Get Preson, and use the person person         = Factory.getbean ("person", person.class);         System.out.println ( person);         System.out.println ("Now start closing the container!" (         (Classpathxmlapplicationcontext) factory). Registershutdownhook ();     }21}

Closing the container uses a hook method that is actually abstractapplicationcontext.

Let's take a look at the results:

Now start initializing the container 2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext preparerefresh Information: refreshing org[email protected]19a0c7c:startup date [Sun May 15:46:20 CST 2014]; Root of context hierarchy2014-5-18 15:46:20 Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions info: Loading XML Bean Definitions from class path resource [Springbeantest/beans.xml] This is the Beanfactorypostprocessor implementation class Builder!! Beanfactorypostprocessor Call Postprocessbeanfactory Method This is the Beanpostprocessor implementation class constructor!! This is the Instantiationawarebeanpostprocessoradapter implementation class Builder!! 2014-5-18 15:46:20 Org.springframework.beans.factory.support.DefaultListableBeanFactory Preinstantiatesingletons Info: pre-instantiating singletons in org.s[email protected]9934d4:defining beans [ Beanpostprocessor,instantiationawarebeanpostprocessor,beanfactorypostprocessor,person]; Root of factory Hierarchyinstantiationawarebeanpostprocessor call Postprocessbeforeinstantiation method "constructor" Invokes the constructor instantiation of person INSTANTIATIONAWAREBEANPOSTPROcessor call postprocesspropertyvalues method "inject attribute" injection attribute address "injection attribute" Injection property name "Injection attribute" injection property phone "Beannameaware interface" Call Beannameaware.setbeanname () "Beanfactoryaware Interface" Call Beanfactoryaware.setbeanfactory () Beanpostprocessor interface Method Postprocessbeforeinitialization Change the properties! "Initializingbean Interface" Call Initializingbean.afterpropertiesset () "Init-method" Call <bean> The Init-method property specifies the initialization method Beanpostprocessor the interface method postprocessafterinitialization the property is changed! Instantiationawarebeanpostprocessor Call Postprocessafterinitialization method Container Initialize successful person [address= Guangzhou, Name= Zhang San, phone= 110] Now start closing the container! "Diposiblebean Interface" calls Diposiblebean.destory () "Destroy-method" Call <bean> the initialization method specified by the Destroy-method property

The life cycle of Spring beans

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.