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.

Table of Contents

1. Bean life cycle
2. Life cycle callback methods

1. Bean life cycle

When container starts – a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some post-initialization steps to get it into a usable state. Same bean life cycle is for spring boot applications as well.

After that, when the bean is no longer required, it will be removed from the IoC container.

Spring bean factory is responsible for managing the life cycle of beans created through spring container.

1.1. Life cycle callbacks

Spring bean factory controls the creation and destruction of beans. To execute some custom code, it provides the call back methods which can be categorized broadly in two groups:

  • Post-initialization call back methods
  • Pre-destruction call back methods

1.1. Life cycle in diagram

Spring Bean Life Cycle
Spring Bean Life Cycle

2. 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

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:

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:

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.

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

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>

	<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.

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. @PostConstruct and @PreDestroy

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...");
	}
}

So this is all about spring bean life cycle inside Spring container. Remember given types of life cycle events, it is a commonly asked spring interview question.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

28 thoughts on “Spring – Bean Life Cycle”

  1. Hi Lokesh, I have one doubt. I have created a small project with 1 bean class, main class and context.xml file. What are the default interfaces implemented by bean behind the scenes if i wont implement any of them manually? Will it implements all the interfaces listed above or any particular mandatory interfaces it will implement ? Please help me in this, as i am stuck in this doubt without moving forward.

    Reply
    • By default, a bean does not implement any of above interfaces. Above interfaces are used for executing code blocks on specific lifecycle event on a bean, and so these are used as and when needed only.

      Reply
      • Thanks a lot Lokesh. I am clear now, as u said they are used when needed only. But,one doubt still persists. Spring container handles each and every beans life cycle defined in context.xml file. What are those mandatory life cycle methods( and these methods belongs to which interfaces ?) called by the Spring container. Example :- I have a single bean class, context file and Test class, and when i run Test class, which are the default methods called on the bean.
        Please bear my questions, which would help me lot :-).

        Reply
        • By default, you can have two methods “init-method” and “destroy-method”. These methods then must be defined inside bean class. Spring framework internally uses reflection to invoke these methods.

          Reply
  2. Nice Explanation. But could you Please discuss more about “Other Aware Interfaces…” and implementation of all these type.

    Thanks
    Tofek

    Reply
  3. Hi,
    Thanks for the above information .It is really helpful.

    I had a requirement in my project, need to run the database scripts through liquibase. There is existing framework to check the change logs and run the change logs . So, just bean definition for this java class is enough to run the liquibase script changes for the entire project . This i have done as below
    <bean id = "lbase" class="com.*.*.**.<> datasource=”datasource” />

    Now, I had another webservice client configuration class which handles the code to read the webservice url and username from database.And the table will be created and loaded with data by the above defined liquibase bean. I have defined this webservice configuration bean as

    The order of defining in spring context file is firstly,liquibase related bean and then wsClientConfig bean is defined.
    now, the doubt is -among these two, which bean is initialized first and which is next?
    For me, error is coming as- no table or view exists while fetching the details of webservice fails.

    Please help in handling this scenario. Thank you

    Reply
  4. I have a doubt.Spring works on the top of the underline java its means JVM .Why spring beans required one more life cycle it means that already jvm will have a life cycle

    Reply
    • JVM does not manage it’s bean’s lifecyle. It’s container for all objects, and it checks which objects are live or dead. JVM never tries to modify the state or behavior of an object. objects are just created inside JVM and cleanup by it when they are no longer referred from other objects. That’s it !!

      Spring bean life cycle is different thing. Here you want to change the state/behavior of bean (or application) whenever an object get’s created or destroyed, or in some specific events. Please note that these events are not JVM triggered events. They are simple “callback methods” when spring’s IOC framework create those bean instances or destroy them.

      Reply
  5. Hi, Lokesh Thanks a lot for this meaningful blog . i have one question which is related to beans life cycle i understood when public void afterPropertiesSet() has called but i have one confusion when public void destroy() will call and who call public void destroy() . and who is responsible to destroy spring bean?

    Reply
  6. Hai am very new to spring .I am getting some problem in Spring bean lifecycle methods.Like
    the out put is
    constructor
    setId
    setName
    This is init-method
    Jul 10, 2014 9:58:35 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2a5330: defining beans [st]; root of factory hierarchy
    constructor
    setId
    setName
    before
    This is init-method
    after
    This is bussinessmethod
    means constructor and setters methods are called two times.what happen will anyone suggest me

    Reply
    • The reason is – spring aop is proxy-based, i.e. the container creates “raw” bean instance and proxy for it (created at runtime via subclassing original bean class) if the bean is affected by AOP rules. So, when proxy object is created, it calls superclass constructor/setters and it looks as two instances are created.

      You notice that “before” and “after” methods are not called because they are run only when actual instance is created. It’s contract provided by Spring’s annotations @PostConstruct and @PreDestroy; OR “init-method” and “destroy-method” attributes of the bean element in configuration file.

      Reply
    • Thanks for your reply.I understand well.Small thing is here am not using Aop concept.i just tries it by implenting BeanPostProcessor interface.And one more thing is if i add bean scope is “singleton” then BeforeInitialization and afterInitialization methods are not called.Plz explain me abt is there any internal relation between bean scopes and BeanPostProcessor interface methods. in BeanLife management.plz reply me.

      Reply
  7. Hi, Thanks for your blog. I have one requirement in my current project like i need to start a new thread in my spring application. In that thread i need to call one of the beans methods. Would you please suggest.

    Reply
    • If the object (thread instance) that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.

      If an object outside the container needs access to the container, you must use singleton pattern for the spring container. Create this singleton bean in application startup, and set the application context reference there in a variable. Now whenever you need a bean, get the context via singleton class, and lookup the bean from application context.

      Reply
  8. Hi, Thanks a lot for this meaningful blog, I have in a problem please help me to solve it.
    Problem: How to prevent serialization in java if the class has implemented Serializable interface. Problem might be like this,
    Class A implements Seralizable{
    }
    class B extends A{
    }

    How to prevent class B to serialize if it have behavior of serialization if someone going to serialize. Please give me innovative solution.

    Hope i will hear you soon.

    Regard’s
    Santosh Srivastava

    Reply
    • Not possible. Reason is that in java super class can not see the internals of child classes. Only child classes can access super class’s fields and methods. Anyway, what kind of design is this in which super class is serializable but child classes are not?? Please refer to “Liskov’s Substitution Principle” in https://howtodoinjava.com/best-practices/solid-principles/

      Anyways, you have following options:

      1) Make super class final so that no one can extend it? [I know it is not what you expect].
      2) Make super class’s field transient, so that if B is serialized then it will have only its state saved.

      Anybody came across this conversation, feel free to engage. 🙂

      Reply
      • In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it

        class MySubClass extends SomeSerializableSuperClass 
        {
        	private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        	throw new NotSerializableException(“Can not serialize this class”);
        	}
        	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        		throw new NotSerializableException(“Can not serialize this class”);
        	}
        	private void readObjectNoData()	throws ObjectStreamException; {
        		throw new NotSerializableException(“Can not serialize this class”);
        	}
        }
        
        Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.