setting list and set values in spring

In this post i’m gonna show you setting List values of pojo by using Spring Framework, it takes less than a minute!

FruitBasket.java


package com.sourceforopensource.pojos;

import java.util.List;

public class FruitBasket {
private String name;
private List<String> fruits;

public FruitBasket(String name, List<String> fruits) {
this.name = name;
this.fruits = fruits;
}

public String toString() {

StringBuilder sb = new StringBuilder();

sb.append(name);
sb.append(" contains:\n");

for(String fruit: fruits) {
sb.append(fruit);
sb.append("\n");
}

return sb.toString();
}
}

beans.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="basket" class="com.sourceforopensource.pojos.FruitBasket">
<constructor-arg value="krishh basket"></constructor-arg>
<constructor-arg>
<list>
<value>apple</value>
<value>banana</value>
<value>orange</value>
<value>kiwi</value>
<value>pear</value>
<value>orange</value>
</list>
</constructor-arg>
</bean>
</beans>

App.java


package com.sourceforopensource.pojos;

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

public class App {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("com/sourceforopensource/beans/beans.xml");

FruitBasket basket = (FruitBasket)context.getBean("basket");

System.out.println(basket);

((ClassPathXmlApplicationContext)context).close();
}

}

Note: similarly we can use set by replacing list with set in beans.xml, but as you already know set wont allow duplicate values.

If you want to set other beans as list  values just use ref tag, like below

<pre><bean id="basket" class="com.sourceforopensource.pojos.FruitBasket">
<constructor-arg value="John's basket"></constructor-arg>
<constructor-arg>
 <list>
   <ref bean="bean1"/>
   <ref bean="bean2"/>
   <ref bean="bean2"/>
   </list> 
</constructor-arg>

Output:

krishh basket contains:
apple
banana
orange
kiwi
pear
orange

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

2 comments

Leave a Reply

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