Spring – Bean Life Cycle

Learn about the Spring bean life cycle. We will learn about bean life cycle stages, initialization and destruction call back methods. We will learn to customize the bean life cycle events using XML configuration as well as Java annotation configuration.

1. What is Life Cycle of a Bean?

A Spring bean needs to be instantiated when the container starts, based on Java or XML bean definition. The framework may also be required to perform some pre and post-initialization steps to get the bean into a usable state.

After that, when the bean is no longer required, it will be removed from the IoC container. Like the initialization phase, the Spring framework may need to perform pre-and post-destruction steps to free the other system resources.

The Spring bean factory is responsible for managing the life cycle callbacks of the beans which are created in the spring containers.

1.1. Life Cycle Callback Methods

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

  1. Post-initialization callback methods
  2. Pre-destruction callback methods
Spring Bean Life Cycle
Spring Bean Life Cycle

2. How to Customize the Bean Life Cycle

Spring framework provides the following four 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

Let’s learn about each way in some detail.

2.1. InitializingBean and DisposableBean 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:

void afterPropertiesSet() throws Exception;

The afterPropertiesSet() method is not a preferable way to initialize the bean because it tightly couples the bean class with the spring container. A better approach is to use “init-method” attribute in bean definition in applicationContext.xml.

Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback before the Spring container destroys the bean.

The DisposableBean interface specifies a single method:

void destroy() throws Exception;

A sample bean implementing the 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 

	public void afterPropertiesSet() throws Exception
		//Bean initialization code

	public void destroy() throws Exception
		//Bean destruction code

2.2. *Aware Interfaces to Add Specific Behavior

Spring offers a range of interfaces that allow the beans to indicate to the container that they require a particular infrastructure dependency.

Each of these Aware interfaces will require us to implement a method to inject the dependency in the bean.

We can summarize these interfaces as :

Aware interface
Method to override
void setApplicationContext (ApplicationContext applicationContext) throws BeansException;
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher);
Set the ApplicationEventPublisher that this object runs in.
void setBeanClassLoader (ClassLoader classLoader);
Callback that supplies the bean class loader to a bean instance.
void setBeanFactory (BeanFactory beanFactory) throws BeansException;
Callback that supplies the owning factory to a bean instance.
void setBeanName(String name);
Set the name of the bean in the bean factory that created this bean.
void setBootstrapContext (BootstrapContext bootstrapContext);
Set the BootstrapContext that this object runs in.
void setLoadTimeWeaver (LoadTimeWeaver loadTimeWeaver);
Set the LoadTimeWeaver of this object’s containing ApplicationContext.
void setMessageSource (MessageSource messageSource);
Set the MessageSource that this object runs in.
void setNotificationPublisher (NotificationPublisher notificationPublisher);
Set the NotificationPublisher instance for the current managed resource instance.
void setPortletConfig (PortletConfig portletConfig);
Set the PortletConfig this object runs in.
void setPortletContext (PortletContext portletContext);
Set the PortletContext that this object runs in.
void setResourceLoader (ResourceLoader resourceLoader);
Set the ResourceLoader that this object runs in.
void setServletConfig (ServletConfig servletConfig);
Set the ServletConfig that this object runs in.
void setServletContext (ServletContext servletContext);
Set the ServletContext that this object runs in.

Java program to show the use of Aware interfaces.

package com.howtodoinjava.task;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class DemoBean implements ApplicationContextAware
        private ApplicationContext ctx;

	public void setApplicationContext(ApplicationContext ctx)
			throws BeansException {
		this.ctx = ctx;

        //Use the context in other bean methods

2.3. Custom init() and destroy() Methods

We can add the default init() and destroy() methods in two ways:

  • Local definitions applicable to a single bean
  • Global definitions applicable to all beans defined in whole beans context

2.3.1. Local definitions

The local init() and destroy() methods are configured as in the given example.

    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"

2.3.2. Global definitions

The container will invoke the global methods for all bean definitions given under <beans> tag. Global overrides are helpful when we have a pattern of defining common method names such as init() and destroy() for all the beans consistently.

This feature helps us 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>

Based on the above local or global overrides, we must write the customInit() and customDestroy() methods in the bean classes as below example.

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 Annotations

From Spring 2.5 onwards, we can use the @PostConstruct and @PreDestroy annotations for specifying the bean life cycle methods.

  • @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 invoked 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
	public void customInit()
		System.out.println("Method customInit() invoked...");

	public void customDestroy()
		System.out.println("Method customDestroy() invoked...");

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

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

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.

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

      • 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 :-).

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

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


  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

  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

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

  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?

  6. Hai am very new to spring .I am getting some problem in Spring bean lifecycle methods.Like
    the out put is
    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
    This is init-method
    This is bussinessmethod
    means constructor and setters methods are called two times.what happen will anyone suggest me

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

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

  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.

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

  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.

    Santosh Srivastava

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

      • 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”);

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.