December 31, 2011

Spring Bean Scope Demo - Prototype & Singleton

1) Create 2 beans - PrototypeBean.java & SingletonBean.java - in the src folder of the web application

package info.icontraining.spring;

public class PrototypeBean {
   private int i;
 
   public PrototypeBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   }
}



package info.icontraining.spring;

public class SingletonBean {

   private int i;
 
   public SingletonBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   } 
}

2) Configure both beans in the WebContent/WEB-INF/applicationContext.xml file - the PrototypeBean bean is configured with the scope attribute set to 'prototype'

<bean id="singleton" class="info.icontraining.spring.SingletonBean" />
 
<bean id="prototype" class="info.icontraining.spring.PrototypeBean" scope="prototype" />

3) Create a client JSP - singletonPrototypeDemo.jsp - in the WebContent folder of the web application

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

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

 SingletonBean s1 = (SingletonBean)factory.getBean("singleton");
 s1.changeValue();
 
 SingletonBean s2 = (SingletonBean)factory.getBean("singleton"); 
 %>
 
 <%= "SingletonBean on Reference-1 after changing value = " + s1.getValue() %><br/>
 <%= "SingletonBean on Reference-2 without changing value = " + s2.getValue() %>

<br/><br/>

<% 
 PrototypeBean p1 = (PrototypeBean)factory.getBean("prototype");
 p1.changeValue();
 
 PrototypeBean p2 = (PrototypeBean)factory.getBean("prototype"); 
 %>

 <%= "PrototypeBean on Reference-1 after changing value = " + p1.getValue() %><br/>
 <%= "PrototypeBean on Reference-2 without changing value = " + p2.getValue() %>

</body>
</html>

4) Test the example with the following URL in the browser

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

No comments:

Post a Comment