Setup and Teardown

We all know the functionality of the init() method in the servlet. We also agree this is one of the best or a fantastic API of the servlet lifecycle. Spring provides the similar configurable support for the BEAN, but note this is not the callback API nor has a mandatory naming (reserve word). This also has a lot of difference in the servlet's init() and this configurable custom initilization method. I generally compare these two since I personaly feel they are similar and it help most of them.

Now lets come to the Spring, after the constructor is used to create the object of the class, we can configure a method to be called by the spring container (init() is called by the servlet container). After the constructor is done with its defined job and we need some other peice of code to invoked which might be used once in the life cycle of the object, we can configure this method as the init-method for this bean.

I found this very useful when we had a different encryption and decription keys for the objects and is independent to the intentions of the bean creation. So I configure this init-method and destroy-method to achieve this. Here is the typical code for the same.






package test.spring.injection;

public class CustomInit {
  
  public CustomInit(){
    System.out.println("This is the default constructor...");
  }
  
  public void setEncryptionKey(){
    System.out.println("Go to DB/Context load the key");
  }
  
  public void broadcastEncryptionKey(){
    System.out.println("Shout you are erased...");
  }

}






<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<beans>
  <bean id="customInit" class="test.spring.injection.CustomInit"
    init-method="setEncryptionKey"
    destroy-method="broadcastEncryptionKey" />
</beans>


The best approach then the above would be to implement the InitializingBean and DisposableBean. Now override the afterPropertiesSet() [implement init-method logic here] and destroy() [implement the destroy-method logic here]. These are the bean lifecycle API's

No comments:

Followers