July 16, 2011

Wiring Collections in a Spring bean

0) Setup the Spring framework in the web application by executing the Hello World example at this link

1) Create the interface for the spring bean, ICollections.java, as follows,

package info.icontraining.spring;

public interface ICollections {
   public void printList();
   public void printMap();
}

2) Create a spring bean class, CollectionsExample.java as follows,

package info.icontraining.spring;

import java.util.*;

public class CollectionsExample implements ICollections {

   List list;
   Map map;
 
   public void printList() {
      for(String s: list) {
         System.out.println(s);
      }
   }
 
   public void printMap() {
      for(String s: map.keySet()) {
         System.out.println(s + ": " + map.get(s));
      }
   }
 
   public void setMyList(List list) {
      this.list = list;
   }
 
   public void setMyMap(Map map) {
      this.map = map;
   }
}

3) Add the following configuration for the spring bean in the applicationContext.xml file in WebContent/WEB-INF folder - this configuration injects a List and a Map into the spring bean.

<bean id="listExample" class="info.icontraining.spring.CollectionsExample">
   <property name="myList">
      <list>
         <value>String 1</value>
         <value>String 2</value>
         <value>String 3</value>
      </list>
   </property>
   <property name="myMap">
      <map>
         <entry key="key1" value="value1" />
         <entry key="key2" value="value2" />
         <entry key="key3" value="value3" />
      </map>
   </property>
</bean>

4) Create a JSP, springTest.jsp as follows,

<%@ 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); ICollections collection = (ICollections)factory.getBean("listExample");
collection.printList();
collection.printMap();
%>

</body>
</html>

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

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

3 comments:

  1. Hi Dinesh,

    Should the property names for the List and the Map be 'list' and 'map' respectively in the applicationContext.xml file instead of 'myList' and 'myMap' to match the spring bean class?

    ReplyDelete
  2. They should be configured as 'myList' and 'myMap' to match the setter injection methods in the spring bean class (CollectionsExample) in this case. The Spring Framework will be able to invoke the setter injections method ( setMyList(..) and setMyMap(..) ) only when the JavaBean property name derived from these methods are an exact match with the property names configured in the applicationContext.xml

    ReplyDelete
  3. OK, thanks. I thought they supposed to match the class properties 'list' and 'map' in the (CollectionsExample) class.

    ReplyDelete