December 31, 2011

Initializing, Destroying Spring Beans & instantiating a Spring Bean through a factory method

1) Create an interface - InitDestroyDemo.java - in the src folder of the web application

package info.icontraining.spring;

public interface InitDestroyDemo {
   public void businessMethod();
}


2) Create a Spring Bean that implements the interface - InitDestroyDemoImpl.java - in the src folder of the web application

package info.icontraining.spring;

public class InitDestroyDemoImpl implements InitDestroyDemo {

   private InitDestroyDemoImpl() { }
 
   public void myInitMethod() {
      System.out.println("Inside Init Method of Spring Bean");
   }
 
   public void businessMethod() {
      System.out.println("Inside Business Method of Spring Bean");
   }
 
   public void myDestroyMethod() {
      System.out.println("Inside Destroy Method of Spring Bean");
   }
 
   public static InitDestroyDemo getInstance() {
      return new InitDestroyDemoImpl();
   }
}


3) Configure the Spring Bean in the WebContent/WEB-INF/applicationContext.xml file

The bean is configured with an initializing method using the init-method attribute, with a destroying method using the destroy-method attribute.

The constructor of the bean is made private, and instantiation is instead done through a static factory method, getInstance() - this is configured using the factory-method attribute

<bean id="initDestroyDemo" class="info.icontraining.spring.InitDestroyDemoImpl" init-method="myInitMethod" destroy-method="myDestroyMethod" factory-method="getInstance" />


4) Create a client JSP - springInitDestroy.jsp - in the WebContent folder of the web application

<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*"%>
<html>
<body>

View output on Server console

 <% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 InitDestroyDemo test = (InitDestroyDemo)factory.getBean("initDestroyDemo");
 test.businessMethod();
 
 %>
</body>
</html>


5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springInitDestroy.jsp

No comments:

Post a Comment