Spring List Elements Example


 

Spring List Elements Example

In this tutorial you will learn about the Spring List Elements

In this tutorial you will learn about the Spring List Elements

Spring <list> Configuration Element

This list element is used to store one or more values. Here <value>, <ref> and <null> elements can be used to set values to the list. <value> element can be used to set simple values like string, <ref> element can be used to provide values as references to other beans, <null> can be used if you want to set null value.

Lets take an example to demonstrate how list element is used.

Product.java: This class contains parts attribute which is the collection of the values of String type.

import java.util.*;

public class Product
{
private Collection<String> parts;

public void setParts(Collection<String> parts) {
this.parts = parts;
}
public Collection<String> getParts() {
return parts;
}
}

 

spring-beans-list.xml: The <list> element is used to provide values to the Collection type property of the Product class. Here <value> element provides those values.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="product" class="Product">
<property name="parts">
<list>
<value>Part 1</value>
<value>Part 2</value>
<value>Part 3</value>
</list>
</property>
</bean>
</beans>

 

AppMain.java: This is the main class which loads the context configuration file spring-beans-list.xml from the class path. Now it gets the product bean from application context which can be used to get property of Collection type. Run the program below and you will get all values from the collection.

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

public class AppMain
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"spring-beans-list.xml"});

Product product = (Product)appContext.getBean("product");

for (String part : product.getParts()) {
System.out.println(part);
}
}
}

Ads