Spring Bean life cycle

Source: Internet
Author: User
Tags getmessage

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may need to perform some initialization to convert it to a usable state. Similarly, when a bean is no longer needed and removed from the container, some cleanup work may also need to be done.

However, there are activities that take place between the instantiation of the bean and the destruction time, but this chapter will only discuss two of the key Bean's lifecycle callback methods that need to be initialized and destroyed by the bean.

To define the installation and removal of a bean, we simply declare the initialization method and/or destroy the method parameter <bean>. The Init-method property specifies a method that is instantiated immediately after the bean is called. Similarly, the Destroy method specifies the method that is called before the bean is removed from the container.

Initialize callback:

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

void throws Exception;

Therefore, it is possible to simply implement the above interface and initialize the work that can be done inside the Afterpropertiesset () method, as follows:

 Public class Implements Initializingbean {   publicvoid  Afterpropertiesset () {      //  Do some initialization   }}

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

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

Here is the definition of the class:

 Public class Examplebean {   publicvoid  init () {      // do some initialization work   }}
destroying callbacks

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

void throws Exception;

Therefore, you can simply implement the above interface and finalize the work that can be done inside the Destroy () method, as follows:

 Public class Implements Disposablebean {   publicvoid  Destroy () {      // do some Destructionwork   }}

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

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

Here is the definition of the class:

 Public class Examplebean {   publicvoid  Destroy () {      // do some destruction work   }}

If you use spring's IOC container in a non-web application environment, such as in a desktop rich client environment; Register to close the hooks in the JVM. Doing so ensures that the shutdown is normal and that all resources are freed to invoke the related destroy method on the singleton bean.

It is not recommended to use Initializingbean or Disposablebean callbacks because the XML configuration provides great flexibility in naming your methods.

For example:

Use the Eclipse IDE, and then follow the steps below to create a spring application:

Steps description
1 Create a project with a name  Springexam ple  and Create a package  com.manongjc  under the  src  folder In the created project.
2 add required Spring libraries using  add External JARs  option as Explaine D in the  Spring Hello World Example  chapter.
3 Create Java classes  HelloWorld  and  Mainapp  under the   COM.MANONGJC  package.
4 Create Beans configuration file  beans.xml  under the  src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file a nd run the application as explained below.

Here is the contents of the Helloworld.java file:

 PackageCOM.MANONGJC; Public classHelloWorld {PrivateString message;  Public voidsetmessage (String message) { This. Message =message; }    Public voidGetMessage () {System.out.println ("Your Message:" +message); }    Public voidinit () {System.out.println ("Bean is going through init."); }    Public voiddestroy () {System.out.println ("Bean would destroy now."); }}

The following is the contents of the Mainapp.java file. Here, you need to register to declare a shutdown Hookregistershutdownhook () method in the Abstractapplicationcontext class. This will ensure a graceful shutdown and call the relevant destroy method.

 PackageCOM.MANONGJC;ImportOrg.springframework.context.support.AbstractApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {Abstractapplicationcontext context=NewClasspathxmlapplicationcontext ("Beans.xml"); HelloWorld obj= (HelloWorld) context.getbean ("HelloWorld");      Obj.getmessage ();   Context.registershutdownhook (); }}

The following are the required init and destroy method configuration file Beans.xml files:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd ">   <BeanID= "HelloWorld"class= "Com.manongjc.HelloWorld"Init-method= "Init"Destroy-method= "Destroy">       < Propertyname= "message"value= "Hello world!"/>   </Bean></Beans>

Once you have created the source and bean configuration file to complete, let's run the application. If all goes well, this will print the following information:

Bean is going through init. Your Message:hello world! Bean would destroy now.
default initialization and destruction methods:

If you have too many beans to initialize and destroy or have a method with the same name, you do not need to declare the initialization method and destroy the method on each bean. The opposite framework provides the flexibility to use the <beans> element Default-init-method and Default-destroy-method properties as follows to configure such situations:

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "Default-init-method= "Init"Default-destroy-method= "Destroy">   <BeanID="..."class="...">       <!--collaborators and configuration for this bean go here -   </Bean></Beans>

Original address: http://www.manongjc.com/spring/spring_bean_life_cycle.html

Related reading:

    • Spring Tutorials
    • What is the Spring framework
    • The architecture of the spring framework
    • Spring Environment Installation Configuration
    • Spring Walkthrough Examples
    • Spring IOC Container and principle
    • Spring Bean Definition
    • Scope of Spring Bean
    • Spring Bean life cycle
    • Spring Beanpostprocessor Interface
    • Spring Bean definition Inheritance
    • Spring Dependency Injection
    • Spring injects internal beans
    • Spring Injection Collection
    • Spring Beans Automatic assembly
    • Spring Event Handling
    • Spring based annotation configuration
    • Spring based Java configuration

Spring Bean life cycle

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.