Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between BeanPostProcessor and init/destroy method in Spring?

Tags:

spring

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?

like image 684
LuckyLuke Avatar asked Mar 25 '12 17:03

LuckyLuke


People also ask

What is the purpose of init-method and destroy method in spring bean?

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.

What is BeanPostProcessor in spring?

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?

Which annotation is used as a substitute of destroy method? Explanation: Using JSR annotation.

When destroy method is called in spring?

The init-method is called after the properties are set by spring container and the destroy-method is called before the JVM is closed.


1 Answers

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.

like image 111
Emil H Avatar answered Sep 28 '22 20:09

Emil H