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>
<%@ 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