Spring Bean Life Cycle

By | | Updated : 2021-03-09 | Viewed : 2438 times

Spring Bean Life Cycle

In this tutorial, we will discuss the life cycle of Spring Beans. What are the steps involved in the life cycle of a bean with the Spring framework? A life cycle of a bean in spring means a number of steps executed sequentially by the Spring Bean factory i.e., IOC container. Let\'s start digging into the basic concepts of Spring Bean life\'s cycle.

Spring Bean Life Cycle

We need to understand first What is spring bean life cycle in Spring. Technically Speaking, Spring bean is managed by Spring Bean factory i.e., Spring IOC container. Spring bean container manages beans from creation to destroy of the bean. This management is performed throughout different phases. These all phases combinedly called as Spring Bean Life Cycle. In other words, Spring Bean Life Cycle is nothing but a number of sequential steps from the step of bean creation to the step of bean destroy.

We can easily observe the Spring bean life cycle using the customization of Spring beans i.e., using bean life cycle call back methods. We will see these callback methods in the next section.

Life cycle callback Methods

There are different ways to set the calls back for customizing the bean in spring. we will look at all types of options.

Using afterPropertiesSet() and destroy()

Here we will look into that InitializingBean, DisposableBean in detail. Please look into the given class for the same implementation.

ASpringBean.java
public class ASpringBean implements InitializingBean, DisposableBean {

	@Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(":::::::<<<<<:::::::  afterPropertiesSet()@InitializingBean    :::::::>>>>>>:::::::");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println(":::::::<<<<<:::::::  destroy()@DisposableBean    :::::::>>>>>>:::::::");
    }
}

Notice here we used InitializingBean, DisposableBean classes and implemented afterPropertiesSet() and destroy() methods. These methods will be called as part of the bean lifecycle execution. You need to configure the config class and Client for executing the above program. You can refer Github repository, please see the output of the above program.

afterPropertiesSet() will be called after creation bean where destroy() will be invoked before destroy of the spring bean. Notice the same result you can see here.

Output of ASpringBean.java
:::::::<<<<<:::::::  constructor@ASpringBean    :::::::>>>>>>:::::::A ASpringBean Bean
:::::::<<<<<:::::::  afterPropertiesSet()@InitializingBean    :::::::>>>>>>:::::::
A ASpringBean Bean
:::::::<<<<<:::::::  destroy()@DisposableBean    :::::::>>>>>>:::::::

Using initMethod and destroy method properties

Two more properties are defined in spring for customizing the bean in Spring. Those are initMethod and destroyMethod properties in @Bean annotation.. These properties have to be configured in the configuration class as we are using annotations. Please see below the given SpringAppConfig Class.

SpringAppConfig.java
@Configuration
public class SpringAppConfig {

    @Bean(initMethod = "aSpringBeanPostConstruct", destroyMethod = "aSpringBeanCleanUp")
    public ASpringBean aSpringBean() {
        return new ASpringBean("ASpringBean");
    }
}

See here we are written SpirngAppConfig class with initMethod, destroyMethod properties. Here aSpringBeanPostConstruct and aSpringBeanCleanUp are method names. So the same name methods should be implemented in ASpringBean class. Please notice the given class for ASpringBean below.

ASpringBean.java
public class ASpringBean {

    public void aSpringBeanPostConstruct() {
        System.out.println(":::::::<<<<<:::::::  aSpringBeanPostConstruct()@ASpringBean    :::::::>>>>>>:::::::" + bSpringBean);
    }


    public void aSpringBeanCleanUp() {
        System.out.println(":::::::<<<<<:::::::  aSpringBeanCleanUp method@ASpringBean    :::::::>>>>>>:::::::" + bSpringBean);
    }
}

If you notice the below given result aSpringBeanPostConstruct() will be invoked after creation of bean but aSpringBeanCleanUp() will be invoked before destroy of bean.

Result of above program
:::::::<<<<<:::::::  constructor@ASpringBean    :::::::>>>>>>:::::::ASpringBean
:::::::<<<<<:::::::  constructor@BSpringBean    :::::::>>>>>>:::::::BSpringBean
:::::::<<<<<:::::::  setBSpringBean@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.definitdestmethods.BSpringBean@175c2241
:::::::<<<<<:::::::  aSpringBeanPostConstruct()@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.definitdestmethods.BSpringBean@175c2241
ASpringBean@displayASpringBean()
:::::::<<<<<:::::::  aSpringBeanCleanUp method@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.definitdestmethods.BSpringBean@175c2241

@PostConstruct and @PreDestroy annotations

@PostConstruct annotation is used as a callback after bean creation whereas @PreDestroy used as a callback prior to bean destroying. Please look at the below give example for the same.

ASpringBean.java
public class ASpringBean {

    @PostConstruct
    public void aSpringBeanPostConstruct() {
        System.out.println(":::::::<<<<<:::::::  aSpringBeanPostConstruct() method  :::::::>>>>>>:::::::");
    }

    @PreDestroy
    public void aSpringBeanCleanUp() {
        System.out.println(":::::::<<<<<:::::::  aSpringBeanCleanUp() method   :::::::>>>>>>:::::::");
    }
}

You can find the output for this example as given below.

Result of above given program
:::::::<<<<<:::::::  constructor@ASpringBean    :::::::>>>>>>:::::::ASpringBean
:::::::<<<<<:::::::  constructor@BSpringBean    :::::::>>>>>>:::::::ASpringBean
:::::::<<<<<:::::::  setBSpringBean@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.annotatedcallbacks.BSpringBean@7c7a06ec
:::::::<<<<<:::::::  aSpringBeanPostConstruct() method  :::::::>>>>>>:::::::
com.docsconsole.tutorials.lifecycle.annotatedcallbacks.BSpringBean@7c7a06ec
:::::::<<<<<:::::::  aSpringBeanCleanUp() method   :::::::>>>>>>:::::::

Spring Bean Aware Interfaces

There are some aware* interfaces defined in Spring framework that are very useful for customizing the beans and will be called in different phases.

ASpringBean.java
public class ASpringBean implements ApplicationContextAware,
        ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
        BeanNameAware, LoadTimeWeaverAware, MessageSourceAware,
        NotificationPublisherAware, ResourceLoaderAware {


		//Need to provide implemented methods
}

These are all interfaces that have different types of methods being invoked in different phases.

Result of above given program
:::::::<<<<<:::::::  constructor@ASpringBean    :::::::>>>>>>:::::::A ASpringBean Bean
:::::::<<<<<:::::::  constructor@BSpringBean    :::::::>>>>>>:::::::BSpringBean
:::::::<<<<<:::::::  setBSpringBean@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.definitdestmethods.BSpringBean@206a70ef
:::::::<<<<<:::::::  setBeanName@BeanNameAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setBeanClassLoader@BeanClassLoaderAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setBeanFactory@BeanFactoryAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setResourceLoader@ResourceLoaderAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setApplicationEventPublisher@ApplicationEventPublisherAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setMessageSource@MessageSourceAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setApplicationContext@ApplicationContextAware    :::::::>>>>>>:::::::

Spring Bean Life Cycle Steps

When you see all types of call back mechanisms in one class we can see an overview of the Spring bean life cycle. So please find the below-given program.

ASpringBean.java
public class ASpringBean implements ApplicationContextAware,
        ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
        BeanNameAware, LoadTimeWeaverAware, MessageSourceAware,
        NotificationPublisherAware, ResourceLoaderAware {

    private String aSpringBeanName;
    private BSpringBean bSpringBean;

    public ASpringBean(String aSpringBeanName) {
    }

    @Autowired
    public void setBSpringBean(BSpringBean bSpringBean) {

    }

    @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

    }
}

The output of the above program is as given below.

Result of the above given programm
:::::::<<<<<:::::::  constructor@ASpringBean    :::::::>>>>>>:::::::A ASpringBean Bean
:::::::<<<<<:::::::  constructor@BSpringBean    :::::::>>>>>>:::::::BSpringBean
:::::::<<<<<:::::::  setBSpringBean@ASpringBean    :::::::>>>>>>:::::::com.docsconsole.tutorials.lifecycle.definitdestmethods.BSpringBean@22ff4249
:::::::<<<<<:::::::  setBeanName@BeanNameAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setBeanClassLoader@BeanClassLoaderAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setBeanFactory@BeanFactoryAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setResourceLoader@ResourceLoaderAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setApplicationEventPublisher@ApplicationEventPublisherAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setMessageSource@MessageSourceAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  setApplicationContext@ApplicationContextAware    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  aSpringBeanPostConstruct() method  :::::::>>>>>>:::::::
:::::::<<<<<:::::::  afterPropertiesSet()@InitializingBean    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  _ASpringBeanPostConstruct() method  :::::::>>>>>>:::::::
:::::::<<<<<:::::::  After Creation of    :::::::>>>>>>:::::::A ASpringBean Bean
:::::::<<<<<:::::::  After registerShutdownHook   :::::::>>>>>>:::::::
:::::::<<<<<:::::::  aSpringBeanCleanUp() method   :::::::>>>>>>:::::::
:::::::<<<<<:::::::  destroy()@DisposableBean    :::::::>>>>>>:::::::
:::::::<<<<<:::::::  ASpringBeanCleanUp() method  :::::::>>>>>>:::::::

The above-given output clearly indicates that different types of mechanisms are executed. So we can prepare the same context as a diagram. Please find below-given spring bean life cycle diagram.

Spring Bean Life Cycle with diagram

The diagram gives a clear idea of the output of the above program in which all mechanisms combined into one class. So here we used different types of aware class as well you can see in the diagram. And the entire code for this example you can find in Github Spring Bean Lifecycle Annotation Example

Leave A Reply