Today we will look into Spring Bean Life Cycle. Spring Beans are the most important part of any Spring application. Spring ApplicationContext is responsible to initialize the Spring Beans defined in spring bean configuration file.

Spring Bean Life Cycle

Spring Context is also responsible for injection dependencies in the bean, either through setter or constructor methods or by spring autowiring.

Sometimes we want to initialize resources in the bean classes, for example creating database connections or validating third party services at the time of initialization before any client request. Spring framework provide different ways through which we can provide post-initialization and pre-destroy methods in a spring bean life cycle.

  1. By implementing InitializingBean and DisposableBean interfaces – Both these interfaces declare a single method where we can initialize/close resources in the bean. For post-initialization, we can implement InitializingBean interface and provide implementation of afterPropertiesSet() method. For pre-destroy, we can implement DisposableBean interface and provide implementation of destroy() method. These methods are the callback methods and similar to servlet listener implementations.This approach is simple to use but it’s not recommended because it will create tight coupling with the Spring framework in our bean implementations.
  2. Providing init-method and destroy-method attribute values for the bean in the spring bean configuration file. This is the recommended approach because of no direct dependency to spring framework and we can create our own methods.

Note that both post-init and pre-destroy methods should have no arguments but they can throw Exceptions. We would also require to get the bean instance from the spring application context for these methods invocation.

Spring Bean Life Cycle – @PostConstruct, @PreDestroy Annotations

Spring framework also support @PostConstruct and @PreDestroy annotations for defining post-init and pre-destroy methods. These annotations are part of javax.annotation package. However for these annotations to work, we need to configure our spring application to look for annotations. We can do this either by defining bean of type org.springframework.context.annotation.CommonAnnotationBeanPostProcessor or by context:annotation-config element in spring bean configuration file.

Let’s write a simple Spring application to showcase the use of above configurations for spring bean life cycle management. Create a Spring Maven project in Spring Tool Suite, final project will look like below image.

spring-bean-life-cycle-project

Spring Bean Life Cycle – Maven Dependencies

We don’t need to include any extra dependencies for configuring spring bean life cycle methods, our pom.xml file is like any other standard spring maven project.

Spring Bean Life Cycle – Model Class

Let’s create a simple java bean class that will be used in service classes.

Spring Bean Life Cycle – InitializingBean, DisposableBean

Let’s create a service class where we will implement both the interfaces for post-init and pre-destroy methods.

Spring Bean Life Cycle – Custom post-init, pre-destroy

Since we don’t want our services to have direct spring framework dependency, let’s create another form of Employee Service class where we will have post-init and pre-destroy spring life cycle methods and we will configure them in the spring bean configuration file.

We will look into the spring bean configuration file in a bit. Before that let’s create another service class that will use @PostConstruct and @PreDestroy annotations.

Spring Bean Life Cycle – @PostConstruct, @PreDestroy

Below is a simple class that will be configured as spring bean and for post-init and pre-destroy methods, we are using @PostConstruct and @PreDestroy annotations.

Spring Bean Life Cycle – Configuration File

Let’s see how we will configure our beans in spring context file.

Notice that I am not initializing employee name in it’s bean definition. Since EmployeeService is using interfaces, we don’t need any special configuration here.

For MyEmployeeService bean, we are using init-method and destroy-method attributes to let spring framework know our custom methods to execute.

MyService bean configuration doesn’t have anything special, but as you can see that I am enabling annotation based configuration for this.

Our application is ready, let’s write a test program to see how different methods get executed.

Spring Bean Life Cycle – Test Program

When we run above test program, we get below output.

Spring Bean Life Cycle Important Points:

  • From the console output it’s clear that Spring Context is first using no-args constructor to initialize the bean object and then calling the post-init method.
  • The order of bean initialization is same as it’s defined in the spring bean configuration file.
  • The context is returned only when all the spring beans are initialized properly with post-init method executions.
  • Employee name is printed as “Pankaj” because it was initialized in the post-init method.
  • When context is getting closed, beans are destroyed in the reverse order in which they were initialized i.e in LIFO (Last-In-First-Out) order.

You can uncomment the code to get bean of type MyEmployeeService and confirm that output will be similar and follow all the points mentioned above.

Spring Aware Interfaces

Sometimes we need Spring Framework objects in our beans to perform some operations, for example reading ServletConfig and ServletContext parameters or to know the bean definitions loaded by the ApplicationContext. That’s why spring framework provides a bunch of *Aware interfaces that we can implement in our bean classes.

org.springframework.beans.factory.Aware is the root marker interface for all these Aware interfaces. All of the *Aware interfaces are sub-interfaces of Aware and declare a single setter method to be implemented by the bean. Then spring context uses setter-based dependency injection to inject the corresponding objects in the bean and make it available for our use.

Spring Aware interfaces are similar to servlet listeners with callback methods and implementing observer design pattern.

Some of the important Aware interfaces are:

  • ApplicationContextAware – to inject ApplicationContext object, example usage is to get the array of bean definition names.
  • BeanFactoryAware – to inject BeanFactory object, example usage is to check scope of a bean.
  • BeanNameAware – to know the bean name defined in the configuration file.
  • ResourceLoaderAware – to inject ResourceLoader object, example usage is to get the input stream for a file in the classpath.
  • ServletContextAware – to inject ServletContext object in MVC application, example usage is to read context parameters and attributes.
  • ServletConfigAware – to inject ServletConfig object in MVC application, example usage is to get servlet config parameters.

Let’s see these Aware interfaces usage in action by implementing few of them in a class that we will configure as spring bean.

Spring *Aware Example Configuration File

Very simple spring bean configuration file.

Spring *Aware Test Program

Now when we execute above class, we get following output.

Console output of the test program is simple to understand, I won’t go into much detail about that.

That’s all for the Spring Bean Life Cycle methods and injecting framework specific objects into the spring beans. Please download sample project from below link and analyze it to learn more about them.

By admin

Leave a Reply