We have already
seen in Spring
Tutorial - Bean Life Cycle in Spring, that how we can call initialization
and destroy methods when the bean is created and destroyed and also how we can
use @PostConstruct and @Predestroy annotations to define the init as well as
destroy method.
With the end of this article we will be able to learn:
1.
What is Spring BeanPostProcessor?
2.
How Spring BeanPostProcessor works?
3.
How to use Spring BeanPostProcessor?
4.
How to register Spring BeanPostProcessor
with BeanFactory?
What is Spring BeanPostProcessor?
Spring
BeanPostProcessor is an interface which provides the callback method which can
be implemented to do initialization work or any process that is needed to be
done after the bean is instantiated, configured and initialized by the spring container.
Multiple spring BeanPostProcessor interfaces can be configured, and their order can also be decided.
How Spring BeanPostProcessor works?
The spring BeanPostProcessor interface works on bean instance, that is, the spring IoC container instantiates
the bean instance, after that spring BeanPostProcessor interface method, does its
work.
The ApplicationContext
itself detects the beans that have implemented spring BeanPostProcessor
interface and register these beans as PostProcessor and upon bean creation, they
are called.
How to use Spring BeanPostProcessor? Example of Spring
BeanPostProcessor
This example shows
how to use Spring BeanPostProcessor in the context of ApplicationContext.
To achieve this, we will create four files HelloWorld.java, InitHelloWorld.java, MainApp.java and Beans.xml
HelloWorld.java
InitHelloWorld.java
MainApp.java
Beans.xml
Once all the files
are created, compile and run the application. Will give the below output.
Output
BeforeInitialization:
Hello World
Bean is getting initialized
AfterInitialization:
Hello World
Your Message:
Hello World
Bean is getting
destroyed
That’s all with
this topic, I hope I have covered all the required information.
The next chapter in this Spring tutorial series will be Spring – Annotation Based Configuration in Spring framework.
0 Comments