In this tutorial you will learn about how to wire Map collection Using References
In this tutorial you will learn about how to wire Map collection Using ReferencesThe <set> element is used to store multiple unique values. Its sub element <ref> element can be used to provide values as references to other beans. Lets take an example to demonstrate how set element is used.
Product.java: The product class contains property named parts which is the collection of the values of Part type.
import java.util.*;
public class Product
{
private List<Part> parts;
public void setParts(List<Part> parts) {
this.parts = parts;
}
public List<Part> getParts() {
return parts;
}
}
Part.java: This is the class the objects of which are being used as the values for the property of List type named parts.
import java.util.*;
public class Part
{
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
spring-beans.xml: The <set> element is used to provide unique values to the Set or List type property of the Product class. Here <ref> element provides those values as references to the Part type objects.
<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">
<set>
<ref bean="part1"/>
<ref bean="part2"/>
<ref bean="part3"/>
</set>
</property>
</bean>
<bean id="part1" class="Part">
<property name="name" value="Part 1"/>
</bean>
<bean id="part2" class="Part">
<property name="name" value="Part 2"/>
</bean>
<bean id="part3" class="Part">
<property name="name" value="Part 3"/>
</bean>
</beans>
AppMain.java: This class loads the context configuration file spring-beans-list.xml from the class path.
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.xml"});
Product product = (Product)appContext.getBean("product");
for (Part part : product.getParts()) {
System.out.println(part.getName());
}
}
}
If we provide two same objects to the set property then it considers only one because of uniqueness feature of set type collection. For example
<bean id="product" class="Product">
<property name="parts">
<set>
<ref bean="part1"/>
<ref bean="part1"/>
<ref bean="part3"/>
</set>
</property>
</bean>
Now in this case the main class prints names of two parts part1 and part 3 only once each.