in Spring

Spring Bean Lifecycle

Introduction

Every spring bean that is created and destroyed when is it not needed goes through well defined steps called bean lifecycle. Knowing what steps the bean goes though can be used in your advantage when needed.

Steps of beans lifecycle are:

  1. Bean is instanted
  2. Beans properties are populated
  3. BeanNameAware’s method setBeanName(String name)  is called
  4. BeanFactoryAware’s method setBeanFactory(BeanFactory beanFactory) is called
  5. ApplicationContextAware’s method setApplicationContext(ApplicationContext applicationContext) is called
  6. BeanPostProcessor’s method postProcessBeforeInitialization
  7. InitializingBeans’s method afterPropertiesAreSet
  8. Custom init method
  9. BeanPostProcessor’s method postProcessAfterInitialization
  10. DisposableBeans’s method destroy() is called
  11. custom destroy-method

Spring bean example

Lets see one example of the bean with all of upper mentioned steps presented and its xml configuration.

We now need to register BeanPostProcessor, first step is to create a class that implements BeanPostProcessor.

Second step is to specify this KnightBeanPostProcessor as a bean in xml ( in this case) like this.

What is awesome is that application context automatically detects for all beans that implement BeanPostProcessor and registers this beans as post processors.

Test

In previous blog post I have shown you how to use ClassPathApplicationContext and run your examples. Lets repeat this example with one adjustment and method call registerShutdownHook, this will enable graceful shutdown and calls to relevant destroy methods.

If we run this example result will be

Spring is awesome (:

Write a Comment

Comment