MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Spring Bean Life Cycle

In this article we will discuss about the Spring Bean Life Cycle.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Spring Bean Life Cycle

The most important feature of Spring is the bean based approach. The Spring bean is created, managed and dispensed by the Spring IoC container. Each Spring bean has a lifecycle and understanding the spring bean lifecycle enables better coding.

The life cycle of a Spring bean is very easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. There are also other activities between initialization and destruction of the bean. These activities take place behind the scenes. . The following are the stages in a bean’s lifecycle.

  1. Instantiate - The Spring container instantiates the bean.
  2. Populate properties- Spring IoC container injects the bean’s properties.
  3. Set Bean Name- Spring container sets the bean name. If the bean implements BeanNameAware, spring container passes the bean’s id to setBeanName() method.
  4. Set Bean Factory-If the bean implements BeanFactoryAware, Spring container passes theBeanFactory to setBeanFactory().
  5. Pre Initialization-This stage is also called the bean postprocess . If there are anyBeanPostProcessors, theSpring container calls the postProcesserBeforeInitialization () method.
  6. Initialize beans- If the bean implements IntializingBean,its afterPropertySet()method is called. If the bean has init method declaration, the specified initialization method is called.
  7. Post Initialization- IfBeanPostProcessors is implemented by the bean, the Spring container calls their postProcessAfterinitalization() method.
  8. Ready to Use- Now the bean is ready to be used by the application.
  9. Destroy- The bean is destroyed during this stage. If the bean implements DisposableBean, the Spring IoC container will call the destroy() method . If a custom destroy () method is defined, the container calls the specified method.

Although there are many stages in the Spring bean lifecycle, this tutorial will discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.

To define setup and teardown methods for a bean, we simply declare the with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that will be called just before a bean is removed from the container.

Initialization callbacks

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

Listing 1: Single method


voidafterPropertiesSet() throws Exception; 

So you can simply implement above interface and initialization work can be done inside afterPropertiesSet() method as follows:

Listing 2: afterPropertiesSet() method


public class SampleBean implements InitializingBean { 
public void afterPropertiesSet() { 
// perform some initialization work here
} 
} 

When using the XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a return void, no argument method signature. The following is small example.

Listing 3: Small Example


<bean id="sampleBean" 
class="com.src.sample.SampleBean" init-method="init"/>

Listing 4: The sample class definition:

public class SampleBean { 
public void init() { 
// do some initialization work 
} 
} 

Destruction callbacks

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

Listing 5: Single Method

void destroy() throws Exception; 

So to enable a destroy callback, simply implement the above interface and finalization work can be done inside destroy() method as follows:

Listing 6: destroy()

public class SampleBean implements DisposableBean { 
public void destroy() { 
// do the work to be performed before bean destruction
} 
} 

When using the XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a return void, no argument method signature. The following is small example.

Listing 7: Small example


<bean id="sampleBean" 
class="com.src.sample.SampleBean" destroy-method="destroy"/>

Listing 8: The class definition:

public class SampleBean { 
public void destroy() { 
// do some destruction work 
} 
} 

If you are using Spring's IoC container in a non-web application environment (as in client desktop environment), it is required to register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on the singleton beans so that all resources are released properly.

It is recommended to avoid using the InitializingBean or DisposableBean callbacks, because XML configuration gives much more flexibility in terms of naming the method.

Example Application

To start off, a working Eclipse IDE should be in place. Once the IDE is ready, follow the following steps to create a Spring application:

  1. Create a project with a name SpringSample and create a package com.src.sample under the src folder in the created project.
  2. Add required Spring libraries using Add External JARs option
  3. Create Java classes HelloWorld and SampleMain under the com.src.sample 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 and run the application as explained below.

Listing 9: Starting Spring Application

packagecom.src.sample; 
public class HelloWorld { 
private String message; 
public void setMessage(String message){ 
this.message = message; 
} 
public void getMessage(){ 
System.out.println("The Greeting Message : " + message); 
} 
public void init(){ 
System.out.println("The Bean is within the init()."); 
} 
public void destroy(){ 
System.out.println("Bean is about to be destroyed now."); 
} 
} 

Following is the content of the SampleMain.java file. Here it is required to register a shutdown hook- registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

Listing 10: SampleMain.java

packagecom.src.sample; 
importorg.springframework.context.support.AbstractApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class SampleMain{ 
public static void main(String[] args) { 
AbstractApplicationContext context = 
newClassPathXmlApplicationContext("Beans.xml"); 
HelloWorldobj = (HelloWorld) context.getBean("helloWorld"); 
obj.getMessage(); 
context.registerShutdownHook(); 
} 
}

Following is the configuration file beans.xml required for init and destroy methods:

Listing 11: beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
<bean id="helloWorld" class="com.src.sample.HelloWorld" init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
</beans>

Once the source files are created and bean configuration files are ready, the application is ready for running. If everything is fine with the created application, the following two lines will print on the sysout.

Listing 12: Printing on the sysout

The Bean is within the init().
The GreetingMessage :Hello World! 
Bean is about to be destroyed now.

Default initialization and destroy methods

If there are too many beans having initialization and / or destroy methods with the same name, there is no need to declare init-method and destroy-method on every individual bean. Instead, the framework provides the facility to configure the init and destroy methods using default-init-method and default-destroy-method attributes on the <beans> element as follows:

Listing 13: <beans>


<beans xmlns="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">
<bean id="..." class="...">
<!-- collaborators and configuration for bean goes here-->
</bean>
</beans>

The Spring Beans lifecycle callbacks allow for custom methods to be hooked to the bean that are invoked by the container. Knowing the available callbacks helps in efficient programming and rich applications.

This is all for today’s article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login