March 10, 2017

#Spring part 3 : Lifecycle Callbacks

registerShutdownHook(): To close the application context, we need to use AbstractApplicationContext which registers the registerShutdownHook() for the Java programme. This will ensure a graceful shutdown and call the relevant destroy methods.It is used for desktop applications, not for the web applications.

Initialization callbacks
InitializingBean tells spring, my bean needs to know when it is initialized. We need to override afterPropertySet() method, after implementing InitializingBean in your bean class, this method is called whenever bean has finished initialization.
public class MyBean implements InitializingBean {
   public void afterPropertiesSet() {
     // do some initialization work

Destruction callbacks
The org.springframework.beans.factory.DisposableBean interface specifies a single method destroy(), which is called when the bean has been destroyed.
public class MyBean implements DisposableBean {
   public void destroy() {
    // do some destruction work

For both initialization and destruction, you need to modify the bean class. Suppose you don't want to implement the interface specific to spring then their is one more option available.

For initialization: Write any method which does the initialization and destruction in in your bean class, e.g:
public void myinit() {
    // do some initialization work

public void mydestroy() {
    // do some destruction work

In the spring.xml, we need to configure init-method and destroy-method, e.g
< bean id = "traingle" class = "com.Traingle" init-method = "myinit" destroy-method = "mydestroy" / >

Default initialization and destroy methods
When you have too many beans having initialization and/or destroy methods with the same name, then you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the element, e.g:
< beans
   default-init-method = "myinit"
   default-destroy-method = "mydestroy" >
   < bean .... />
   < bean .... />
< /beans >

What will happen when we enable both (XML based and implementing interfaces) types of  initialization and destruction callbacks?

During initialization, first InitializingBean init() method is called, then our myinit(), which we have configured in XML is called.  And during destruction, DisposableBean's destroy() is called, and then mydestroy() is called.

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory