Wednesday, 6 March 2019

Spring - Bean Life Cycle

In this article, learn about Spring bean life cycle. We will learn about life cycle stages, initialization and destroy call back methods. We will learn to control the bean life cycle events using XML configuration as well as annotation configuration.

1. Types of bean life cycle events

Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans consist of call back methods which can be categorized broadly in two groups:
  • Post initialization call back methods
  • Pre destruction call back methods

1.1. Spring bean life cycle diagram




Spring Bean Life Cycle
Spring Bean Life Cycle

2. Spring Bean Life Cycle Callback Methods

Spring framework provides following 4 ways for controlling life cycle events of a bean:
  1. InitializingBean and DisposableBean callback interfaces
  2. *Aware interfaces for specific behavior
  3. Custom init() and destroy() methods in bean configuration file
  4. @PostConstruct and @PreDestroy annotations

2.1. InitializingBean and DisposableBean callback interfaces

The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.
The InitializingBean interface specifies a single method:
InitializingBean.java
void afterPropertiesSet() throws Exception;
This is not a preferrable way to initialize the bean because it tightly couple your bean class with spring container. A better approach is to use “init-method” attribute in bean definition in applicationContext.xml file.
Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed.
The DisposableBean interface specifies a single method:
DisposableBean.java
void destroy() throws Exception;
A sample bean implementing above interfaces would look like this:
package com.howtodoinjava.task;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class DemoBean implements InitializingBean, DisposableBean
{
    //Other bean attributes and methods
     
    @Override
    public void afterPropertiesSet() throws Exception
    {
        //Bean initialization code
    }
     
    @Override
    public void destroy() throws Exception
    {
        //Bean destruction code
    }
}

2.2. *Aware interfaces for specific behavior

Spring offers a range of *Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure dependency. Each interface will require you to implement a method to inject the dependency in bean.
These interfaces can be summarized as :
AWARE INTERFACEMETHOD TO OVERRIDEPURPOSE
ApplicationContextAwarevoid setApplicationContext(ApplicationContext applicationContext) throws BeansException;Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
ApplicationEventPublisherAwarevoid setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher);Set the ApplicationEventPublisher that this object runs in.
BeanClassLoaderAwarevoid setBeanClassLoader(ClassLoader classLoader);Callback that supplies the bean class loader to a bean instance.
BeanFactoryAwarevoid setBeanFactory (BeanFactory beanFactory) throws BeansException;Callback that supplies the owning factory to a bean instance.
BeanNameAwarevoid setBeanName(String name);Set the name of the bean in the bean factory that created this bean.
BootstrapContextAwarevoid setBootstrapContext(BootstrapContext bootstrapContext);Set the BootstrapContext that this object runs in.
LoadTimeWeaverAwarevoid setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver);Set the LoadTimeWeaver of this object’s containing ApplicationContext.
MessageSourceAwarevoid setMessageSource(MessageSource messageSource);Set the MessageSource that this object runs in.
NotificationPublisherAwarevoid setNotificationPublisher(NotificationPublisher notificationPublisher);Set the NotificationPublisher instance for the current managed resource instance.
PortletConfigAwarevoid setPortletConfig (PortletConfig portletConfig);Set the PortletConfig this object runs in.
PortletContextAwarevoid setPortletContext(PortletContext portletContext);Set the PortletContext that this object runs in.
ResourceLoaderAwarevoid setResourceLoader(ResourceLoader resourceLoader);Set the ResourceLoader that this object runs in.
ServletConfigAwarevoid setServletConfig (ServletConfig servletConfig);Set the ServletConfig that this object runs in.
ServletContextAwarevoid setServletContext(ServletContext servletContext);Set the ServletContext that this object runs in.
Java program to show usage of aware interfaces to control string bean life cycle.
DemoBean.java
package com.howtodoinjava.task;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
public class DemoBean implements ApplicationContextAware,
        ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
        BeanNameAware, LoadTimeWeaverAware, MessageSourceAware,
        NotificationPublisherAware, ResourceLoaderAware
{
    @Override
    public void setResourceLoader(ResourceLoader arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setNotificationPublisher(NotificationPublisher arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setMessageSource(MessageSource arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setLoadTimeWeaver(LoadTimeWeaver arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setBeanName(String arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        // TODO Auto-generated method stub
    }
    @Override
    public void setBeanClassLoader(ClassLoader arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        // TODO Auto-generated method stub
    }
}

2.3. Custom init() and destroy() methods in bean configuration XML file

The default init and destroy methods in bean configuration file can be defined in two ways:
  • Bean local definition applicable to a single bean
  • Global definition applicable to all beans defined in beans context
2.3.1. Bean local definition
Local definition is given as below.
beans.xml
<beans>
    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"
                    init-method="customInit"
                    destroy-method="customDestroy"></bean>
</beans>
2.3.2. Global definition
Where as global definition is given as below. These methods will be invoked for all bean definitions given under <beans> tag. They are useful when you have a pattern of defining common method names such as init() and destroy() for all your beans consistently. This feature helps you in not mentioning the init and destroy method names for all beans independently.
<beans default-init-method="customInit" default-destroy-method="customDestroy">  
        <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>
</beans>
Java program to show methods configured in bean XML configuration file.
DemoBean.java
package com.howtodoinjava.task;
public class DemoBean
{
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }
    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}

2.4. Spring Bean Life Cycle – @PostConstruct and @PreDestroy annotations

Spring 2.5 onwards, you can use annotations also for specifying life cycle methods using @PostConstruct and @PreDestroy annotations.
  • @PostConstruct annotated method will be invoked after the bean has been constructed using default constructor and just before it’s instance is returned to requesting object.
  • @PreDestroy annotated method is called just before the bean is about be destroyed inside bean container.
Java program to show usage of annotation configuration to control using annotations.
package com.howtodoinjava.task;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class DemoBean
{
    @PostConstruct
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }
     
    @PreDestroy
    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}

No comments:

Post a Comment

Unity Top Download

Latest post

An Introduction to Hybris from basics

An Introduction to Hybris from basics:  -- ecommerce site and PCM(Product content Management) solutions. eg. croma website.  -- having sear...

Popular posts