Spring Bean Life Cycle – Callback Interface, Custom Method, Annotation, Aware Interface

Spring Bean Life Cycle is very important because in many applications, we want to create some operations before initializing a Bean or make some operations before bean’s destruction.

This tutorial introduce four ways to control life cycle events of a Bean.

I. Demo

II. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE

III. Overview
1. Bean Life Cycle


2. Goal

To build a simple application that expresses how we can provide post-initialization and pre-destroy methods in a Spring Bean Life Cycle.

3. Project Structure


4. Step to do

– Create Spring Boot project
– Create Class for Bean
– Create Services
– Create Spring Bean Configuration Files
– Add commands to SpringBootApplication Class
– Run Spring Boot Application & Enjoy Result

IV. Practice
1. Create Spring Boot project

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each field:

Click Next and Finish. Spring Boot project will be created successfully.

2. Create Class for Bean

Under package bean, create class Customer:

3. Create Services

Under package service, create service classes:

Content of CustomerServiceImpCustomMethod.java

InitializingBean and DisposableBean callback interfaces will be implemented to override 2 methods afterPropertiesSet() and destroy().
custom init() and destroy() methods are defined in configuration bean file (by init-method and destroy-method) and implemented under customInitBean() and customDestroyBean().
@PostConstruct and @PreDestroy annotations which are part of javax.annotation package will be annotated to methods: postConstruct() and preDestroy(). To use those annotations, we must add bean for org.springframework.context.annotation.CommonAnnotationBeanPostProcessor in Bean Configuration File.

– We also use other Aware interfaces for specific behavior such as: setBeanName, setBeanClassLoader, setBeanFactory, setApplicationContext

Content of CustomerServiceImpAwareInterface.java

4. Create Spring Bean Configuration Files

Under src/main/resources, create two XML files:



5. Add commands to SpringBootApplication Class

Open SpringBeanLifeCycleApplication.java, change the content inside:

6. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results in Console Screen:

IV. Source Code


Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *