Spring Bean Post Processors


The BeanPostProcessor interface helps us provide our own methods before the initialization of beans and likewise after the initialization of the bean.

BeanPostProcessor are common for all beans in the container where it is defined, so it is different from @PostConstruct, InitializingBean and custom init method which are defined on the bean itself.

Related Article: Spring Bean Life Cycle

I. Technology

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

II. Overview
1. Where is it?

The IoC container calls BeanPostProcessor.postProcessBeforeInitialization() before @PostConstruct and InitializingBean.afterPropertiesSet() method, then calls BeanPostProcessor.postProcessAfterInitialization() (after custom init method).

2. Goal

To build a simple application that expresses how we can use Bean Post Processor methods in a Spring Bean Life Cycle.

3. Project Structure


4. Step to do

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

III. Practice
1. Create Spring Boot project

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

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

2. Create Class for Bean

Under package bean, create class Customer.

Content of Customer.java

Then, create MyBeanPostProcessor.java to handle BeanPostProcessor operations.

3. Create Service

Under package service, create CustomerService.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.

4. Create Spring Bean Configuration File

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

5. Add commands to SpringBootApplication Class

Open SpringBeanPostProcessorsApplication.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


By grokonez | September 12, 2016.

Last updated on September 23, 2018.

Related Posts

Got Something To Say:

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