Spring Tutorial-spring Bean life cycle

Source: Internet
Author: User
Tags constructor xmlns

It's easy to understand the Spring Bean's life cycle. When a bean is instantiated, it may need to perform some initialization to convert it to a usable state. Similarly, some cleanup work may be required when the bean is no longer needed and removed from the container.

The full life cycle of the bean undergoes various method invocations, which can be divided into the following categories: The Bean's Own method: This includes the method that the bean itself invokes and the <bean> in the configuration file Init-method and Destroy-method Specify method Bean Lifecycle Callback interface method: This includes Beannameaware, Beanfactoryaware, Applicationcontextaware, Initializingbean and Diposablebean methods of these interfaces container-level life-cycle interface methods: This includes both the Beanpostprocessor and the Beanfactorypostprocessor interface implementations, Their implementation class is generally referred to as the "post processor".


This tutorial is based on the Spring Framework 4.3.3.RELEASE.

Bean Initialization Callback

The Org.springframework.beans.factory.InitializingBean interface Specifies a single method:

void Afterpropertiesset () throws Exception;

Therefore, you can simply implement the above interface and initialization work can be performed in the Afterpropertiesset () method, as follows:

public class Examplebean implements Initializingbean {public
   void Afterpropertiesset () throws Exception {
      //do S ome initialization Work
   }
}

In the case of XML-based configuration metadata, you can use the Init-method property to specify a name with a void parameterless method. For example:

<bean id= "Examplebean" 
         class= "examples. Examplebean "init-method=" Init "/>

The following is the definition of the Examplebean class:

public class Examplebean {public
   void init () {
      //Does some initialization work
   }
}
Bean Destroy Callback

The Org.springframework.beans.factory.DisposableBean interface Specifies a single method:

void Destroy () throws Exception;

Therefore, you can simply implement the above interface and end the work can be performed in the Destroy () method, as follows:

public class Examplebean implements Disposablebean {public
   void Destroy () throws Exception {
      //do some destructi On work
   }
}

In the case of XML-based configuration metadata, you can use the Destroy-method property to specify a name with a void parameterless method. For example:

<bean id= "Examplebean"
         class= "examples. Examplebean "destroy-method=" Destroy "/>

The following is the definition of the Examplebean class:

public class Examplebean {public
   void Destroy () {
      //Does some destruction work
   }
}
Example

The following is a simple spring bean that demonstrates the bean's life cycle with the following code:

Package com.bytebeats.spring.lifecycle; /** * ${description} * * @author Ricky Fung * @create 2016-12-28 22:46 * Import org.springframework.beans.BeansExcep
tion;
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;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.ApplicationContextAware; /** * ${description} * * @author Ricky Fung * @create 2016-12-28 22:44 * public class Examplebean implements BEANFAC Toryaware, Beannameaware, Applicationcontextaware, Initializingbean, Disposablebean {private BeanFactory bea
    Nfactory;
    Private String Beanname;

    Private ApplicationContext ApplicationContext;
    Public Examplebean () {System.out.println ("the constructor" calls the person's constructor instantiation "); }//This isBeanfactoryaware interface method @Override public void Setbeanfactory (Beanfactory beanfactory) throws Beansexception {
        System.out. println ("Beanfactoryaware Interface" calls Beanfactoryaware.setbeanfactory () ");
    This.beanfactory = beanfactory; }//This is the Beannameaware interface method @Override public void Setbeanname (String beanname) {System.out.println ("" is
        Annameaware interface "Call Beannameaware.setbeanname ()");
    This.beanname = Beanname; }//This is the Applicationcontextaware interface method @Override public void Setapplicationcontext (ApplicationContext application Context) throws Beansexception {System.out.println ("Applicationcontextaware interface" Call Applicationcontextaware.setappli
        Cationcontext () ");
    This.applicationcontext = ApplicationContext; }//This is the Initializingbean interface method @Override public void Afterpropertiesset () throws Exception {System.out.
    println ("Initializingbean Interface" calls Initializingbean.afterpropertiesset () "); }//Thisis the Diposiblebean interface method @Override public void Destroy () throws Exception {System.out.println ("" Diposiblebean interface
    "Call Diposiblebean.destory ()"); }//The initialization method specified by the Init-method property of <bean> public void Initmethod () {System.out.println ("Init-method" Call &
    lt;bean> the Init-method attribute specified by the initialization method "); }//The initialization method specified by the Destroy-method property of <bean> public void Destroymethod () {System.out.println ("" Destroy-m
    Ethod "Call <bean> the Destroy-method property of the specified initialization method");
 }

}


The configuration file Applicationcontext.xml is as follows:

<?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:context= "http://www.springframework.org/ Schema/context "
       xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans.xsd
        Http://www.springframework.org/schema/context/http Www.springframework.org/schema/context/spring-context-4.0.xsd ">

    <context:annotation-config/>
    <context:component-scan base-package= "com.bytebeats.spring.lifecycle"/>

    <bean id= "Examplebean" class = "Com.bytebeats.spring.lifecycle.ExampleBean" init-method= "Initmethod"
          destroy-method= "Destroymethod" scope= "Singleton"/>

</beans>


The test classes are as follows:

public class App {public

    static void Main (string[] args) {

        Classpathxmlapplicationcontext context = new ClassPath Xmlapplicationcontext ("Applicationcontext.xml");
        System.out.println ("Spring container Initialization succeeded");

        Examplebean Examplebean = (Examplebean) context.getbean ("Examplebean");
        System.out.println (Examplebean);

        try {
            TimeUnit.SECONDS.sleep (5);
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        }
        System.out.println ("Spring container begins to close");
        Context.close ();
    }
}


The results of the operation are as follows:

December 28, 2016 11:06:31 pm Org.springframework.context.support.ClassPathXmlApplicationContext Preparerefresh Info: refreshing org.springframework.context.support.classpathxmlapplicationcontext@4e1557af:startup date [Wed Dec 28 23:06:31 CST 2016]; Root of the context hierarchy December 28, 2016 11:06:31 pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions info: Loading XML Bean Definitions from class path resource [Applicationcontext.xml] "constructor" calls the constructor of the person Instantiate "Beannameaware Interface" Call Beannameaware.setbeanname () "Beanfactoryaware Interface" Call Beanfactoryaware.setbeanfactory () " Applicationcontextaware interface "Call Applicationcontextaware.setapplicationcontext ()" Initializingbean interface "
Call Initializingbean.afterpropertiesset () "Init-method" Call <bean> the initialization method specified by the Init-method property of the spring container initialization succeeded COM.BYTEBEATS.SPRING.LIFECYCLE.EXAMPLEBEAN@390F9EB5 Spring Container started closing December 28, 2016 11:06:36 pm Org.springframework.context.support.ClassPathXmlApplicationContext doclose Info: Closing Org.springframework.context.support.ClAsspathxmlapplicationcontext@4e1557af:startup Date [Wed Dec 23:06:31 CST 2016]; Root of context hierarchy "Diposiblebean interface" Call Diposiblebean.destory () "Destroy-method" Call <bean> The Destroy-method property specifies the initialization method

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.