Spring Collections Example

This tutorial explains how to use the collections API with Spring configurations. Spring provides out of the box support for all the collections classes like List, Set, Map and Properties for injecting the objects. There is a corresponding elements in the spring configuration file to pass the values to the Java objects. This tutorial passes simple string objects to the collections classes, however you can use the custom objects to store in the collections. Lets look at the example below.

1. Spring Bean and Collections


package javabeat.net.core.ioc;

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

public class SpringCollectionsExample {
	private List<Object> lists;
	private Set<Object> sets;
	private Map<Object, Object> maps;
	private Properties pros;
	public List<Object> getLists() {
		return lists;
	public void setLists(List<Object> lists) {
		this.lists = lists;
	public Set<Object> getSets() {
		return sets;
	public void setSets(Set<Object> sets) {
		this.sets = sets;
	public Map<Object, Object> getMaps() {
		return maps;
	public void setMaps(Map<Object, Object> maps) {
		this.maps = maps;
	public Properties getPros() {
		return pros;
	public void setPros(Properties pros) {
		this.pros = pros;


2. Spring Configuration with Collections


<beans xmlns="http://www.springframework.org/schema/beans"

	<context:component-scan base-package="javabeat.net.core.ioc"/>
	<bean id="collectionsExampleBean" class="javabeat.net.core.ioc.SpringCollectionsExample">
		<property name="lists">
				<value>List Object 1</value>
				<value>List Object 2</value>
		<property name="sets">
				<value>Set Object 1</value>
				<value>Set Object 2</value>
		<property name="maps">
				<entry key="Key 1" value="Value 1"/>
				<entry key="Key 2" value="Value 2"/>
				<entry key="Key 3" value="Value 3"/>
		<property name="pros">
				<prop key="Prop Key 1">Value 1</prop>
				<prop key="Prop Key 2">Value 2</prop>

3. Spring Context Loader and Access Collections


package javabeat.net.core.ioc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextLoader {
	public static void main (String args[]){
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
		SpringCollectionsExample collectionsExample = (SpringCollectionsExample)applicationContext.getBean("collectionsExampleBean");

If you run the application you would see the following result:

[List Object 1, List Object 2]
[Set Object 1, Set Object 2]
{Key 1=Value 1, Key 2=Value 2, Key 3=Value 3}
{Prop Key 2=Value 2, Prop Key 1=Value 1}

If you have any thoughts, please share it in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!