Spring Wire Array Type To List Element Example


 

Spring Wire Array Type To List Element Example

In this tutorial you will learn about the Wire Array Type To List Element

In this tutorial you will learn about the Wire Array Type To List Element

Spring <list> Configuration Element to wire Array type property

The list element is used to store multiple values.

Its sub elements, which can be used to set values to the list, are as follows:

1. <value> element can be used to set simple values like string

2. <ref> element can be used to provide values as references to other beans and

3. <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 of String array type.

import java.util.*;

public class Product
{
private String[] parts;

public void setParts(String[] parts) {
this.parts = parts;
}
public String[] getParts() {
return parts;
}
}

 

spring-beans-list.xml: The <list> element is used to provide values to the String arry 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 A</value>
<value>Part B</value>
<value>Part C</value>
</list>
</property>
</bean>
</beans>

 

AppMain.java: This main class loads the context configuration file "spring-beans-list.xml" from the class path. Its product bean is used to get property of String array type.

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