What is the difference between implementing the BeanPostProcessor
interface and either using the init
/destroy
method attributes in the XML configuration file in Spring or implementing InitializingBean
/DisposableBean
interface?
The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container.
Spring's BeanPostProcessor gives us hooks into the Spring bean lifecycle to modify its configuration. BeanPostProcessor allows for direct modification of the beans themselves. In this tutorial, we're going to look at a concrete example of these classes integrating Guava's EventBus.
Which annotation is used as a substitute of destroy method? Explanation: Using JSR annotation.
The init-method is called after the properties are set by spring container and the destroy-method is called before the JVM is closed.
This is pretty clearly explained in the Spring documentation about the Container Extension Points.
The BeanPostProcessor interface defines callback methods that you can implement to provide your own (or override the container's default) instantiation logic, dependency-resolution logic, and so forth. If you want to implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean, you can plug in one or more BeanPostProcessor implementations.
So in essence the method postProcessBeforeInitialization
defined in the BeanPostProcessor gets called (as the name indicates) before the initialization of beans and likewise the postProcessAfterInitialization
gets called after the initialization of the bean.
The difference to the @PostConstruct
, InitializingBean
and custom init
method is that these are defined on the bean itself. Their ordering can be found in the Combining lifecycle mechanisms section of the spring documentation.
So basically the BeanPostProcessor can be used to do custom instantiation logic for several beans wheras the others are defined on a per bean basis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With