Spring Collections

In this article, we will discuss how to use the features of collections in Spring application for injecting list/set of values. So far, we have tried & tested simple primitive types using ‘value’ attribute or referencing objects using ‘ref’ attribute of <bean> tag

Various collection types supported by Spring are

Collection Types Element Description
List <list></list> Helps in injecting list of values, allowing duplicates
Set <set></set> Helps in injecting set of values, but no duplicates are allowed here
Map <map></map> Helps in injecting name-value pairs of any type
Properties <props></props> Helps in injecting name-value pairs of only String type

Refer here for more details on spring collections

Let’s see a detailed example comprising all the collection types

 

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Maven 3.0.4
  • Spring-4.0.0-RELEASE

Mavenize or download required jars

Add Spring-4.0.0 dependencies to the pom.xml

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>${spring.version}</version>
</dependency>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath

  • spring-core-4.0.0-RELEASE
  • spring-context-4.0.0-RELEASE
  • spring-beans-4.0.0-RELEASE
  • spring-aop-4.0.0-RELEASE
  • spring-expression-4.0.0-RELEASE
  • commons-logging-1.1.1
  • aopalliance-1.0

Let’s see coding in action

 

Create simple Address class

Address class with three member variables and it’s setter/getter and overridden toString() method to print the output in the desired format

Address.java

package com.spring.series.collections;

public class Address {

	private String city;
	private String state;
	private String zipcode;

	/**
	 * getter and setter
	 */
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	@Override
	public String toString() {
		return "Address=[" +
				"city=" 	+ city  	+ "," +
				"state="  + state   + "," +
				"zipcode="  	+ zipcode   	+
				"]";
	}
}

Employee class

Employee class with all four collection types as member variables and its setter/getter

Employee.java

package com.spring.series.collections;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Employee {

	// collection types as member variable
	private List<Object> listAddress;
	private Set<Object> setAddress;
	private Map<Object, Object> mapAddress;
	private Properties propsAddress;

	/**
	 * getter and setter
	 */
	public List<Object> getListAddress() {
		return listAddress;
	}
	public void setListAddress(List<Object> listAddress) {
		this.listAddress = listAddress;
	}
	public Set<Object> getSetAddress() {
		return setAddress;
	}
	public void setSetAddress(Set<Object> setAddress) {
		this.setAddress = setAddress;
	}
	public Map<Object, Object> getMapAddress() {
		return mapAddress;
	}
	public void setMapAddress(Map<Object, Object> mapAddress) {
		this.mapAddress = mapAddress;
	}
	public Properties getPropsAddress() {
		return propsAddress;
	}
	public void setPropsAddress(Properties propsAddress) {
		this.propsAddress = propsAddress;
	}
}

Create Spring Bean Configuration file (Spring XML)

Address bean is very simple & straightforward to understand, this is referenced from employee bean

Employee bean with four collection viz., <list>, <set>, <map>, <props>

Except <props> collection types, all other types got three values in the following ways

  1. declaring values directly using ‘value’ attribute
  2. referencing the ‘address’ bean using ‘ref’ attribute
  3. inner bean concept for third  value

For Properties, both name/value pairs are String, where we got location as keys and its OHIO cities are their values

SpringContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- employee bean definition goes here -->
	<bean id="employee" class="com.spring.series.collections.Employee">

		<!-- java.util.List -->
		<property name="listAddress">
			<list>
				<value>ListAddress1</value>
				<ref bean="address" />
				<bean class="com.spring.series.collections.Address">
					<property name="city" value="Kingsfordweg" />
					<property name="state" value="Amsterdam" />
					<property name="zipcode" value="1043" />
				</bean>
			</list>
		</property>

		<!-- java.util.Set -->
		<property name="setAddress">
			<set>
				<value>SetAddress1</value>
				<ref bean="address" />
				<bean class="com.spring.series.collections.Address">
					<property name="city" value="Kingsfordweg" />
					<property name="state" value="Amsterdam" />
					<property name="zipcode" value="1043" />
				</bean>
			</set>
		</property>

		<!-- java.util.Map -->
		<property name="mapAddress">
			<map>
				<entry key="Map_Key_1" value="MapAddress1" />
				<entry key="Map_Key_2" value-ref="address" />
				<entry key="Map_Key_3">
					<bean class="com.spring.series.collections.Address">
						<property name="city" value="Kingsfordweg" />
						<property name="state" value="Amsterdam" />
						<property name="zipcode" value="1043" />
					</bean>
				</entry>
			</map>
		</property>

		<!-- java.util.Properties -->
		<property name="propsAddress">
			<props>
				<prop key="location1">Columbus</prop>
				<prop key="location2">Delaware</prop>
				<prop key="location3">Dublin</prop>
			</props>
		</property>
	</bean>

	<!-- address bean definition goes here -->
	<bean id="address" class="com.spring.series.collections.Address">
		<property name="city" value="Columbus" />
		<property name="state" value="OHIO" />
		<property name="zipcode" value="43211" />
	</bean>

</beans>

Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application

Project Structure in Eclipse (Package Explorer view)

SpringCollections

Test the Application that’s exactly …. Run it!

Let’s test using ApplicationContext

Simple test-class. Self explanatory !!

TestEmployee.java

package com.spring.series.collections;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestEmployee {

	public static void main(String[] args) {
		testSpringCollections();
	}

	private static void testSpringCollections(){

		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/collections/SpringCollections.xml");
		Employee employee = (Employee) applicationContext.getBean("employee");

		System.out.println("List:\n"+ employee.getListAddress());
		System.out.println("\nSet:\n"+ employee.getSetAddress());
		System.out.println("\nMap:\n"+ employee.getMapAddress());
		System.out.println("\nProps:\n"+ employee.getPropsAddress());
	}
}

Output in console

Aug 03, 2014 6:28:08 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6844c4a4: startup date [Sun Aug 03 18:28:08 IST 2014]; root of context hierarchy
Aug 03, 2014 6:28:09 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/spring/series/collections/SpringCollections.xml]

List:
[AnyValue, Address=[city=Columbus,state=OHIO,zipcode=43211], Address=[city=Kingsfordweg,state=Amsterdam,zipcode=1043]]

Set:
[AnyValue, Address=[city=Columbus,state=OHIO,zipcode=43211], Address=[city=Kingsfordweg,state=Amsterdam,zipcode=1043]]

Map:
{Map_Key_1=AnyValue, Map_Key_2=Address=[city=Columbus,state=OHIO,zipcode=43211], Map_Key_3=Address=[city=Kingsfordweg,state=Amsterdam,zipcode=1043]}

Props:
{location1=Columbus, location3=Dublin, location2=Delaware}

Download project

Spring Collections (3kB)

Happy Coding !!
Happy Learning !!