Search in the document preview

07 - Spring Bean Life Cycle
TOC

• 06 - Spring Bean Scopes
• 08 - Spring BeanPost Processors

7.1 Overview of Spring Bean Life Cycle
Life of traditional java objects starts on calling new operator which instantiates the object
and finalize() method is getting called when the object is eligible for garbage collection.
Life cycle of Spring beans are different as compared to traditional java objects.

Spring framework provides the following ways which can be used to control the lifecycle
of bean:

Below diagram shows the complete lifecycle methods (from instantiate to Ready To use

)

Following diagram shows the method calling at the time of destruction.

7.2 InitializingBean and DisposbleBean callback
interfaces

• InitalizingBean interface is defined under org.springframework.beans.factory
package and declares a single method where we can be used to add any
initialization related code. Any bean implementing InitalizingBean needs to
provide an implementation of afterPropertiesSet() method. Signature of method
is:

void afterPropertiesSet() throws Exception;

• Similarly DisposableBean interface is defined under the
org.springframework.beans.factory and declares a single method which gets
executed when bean is destroyed and can be used to add any cleanup related
code. Any bean implementing DisposableBean needs to provide an
implementation of destroy() method. Signature of method is :

void destroy() throws Exception;

This approach is simple to use but it’s not recommended because it will create
tight coupling with the Spring framework in our bean implementations.

7.4 Custom init() and destroy() methods in bean
configuration file
Implementing InitalizingBean and DisposableBean interface is simple to use but create
tight coupling with the Spring framework in our bean implementations.

Alternatively we can init-method and destroy-method attribute values for the bean in
the spring bean configuration file. This is the recommended approach because of no
direct dependency to spring framework and we can create our own methods.

Note: Both post-init and pre-destroy methods should have no arguments but they can
throw Exceptions

?

1

2

3

4

5

6

<beans>

<bean id="bean_id" class="bean.class"

init-method="customInitmethod"

destroy-method="customDestroymethod">

</bean>

</beans>

We can configure the default init-method and destroy-method which will be applied on
all the beans .They are useful when we have a pattern of defining common method
names such as init() and destroy() for all your beans consistently.