Friday, January 10, 2014

Spring Course: V15 List of Beans

lets say that we have the following class

public class Jungle {
private Animal largest;
private List<Animal> animals;


public void setAnimals(List<Animal> animals) {
this.animals = animals;
}
.....
}

as you can see setAnimals takes List<Animal> as input, where Animal is another class defined as follows:

public class Animal {
private String name;
private String type;
...
}

lets say that you have the following Animal beans

<bean id="lion" class="com.caveofprogramming.spring.test.Animal">
<property name="name" value="Igor"></property>
<property name="type" value="lion"></property>
</bean>
<bean id="elephant" class="com.caveofprogramming.spring.test.Animal">
<property name="name" value="Richard"></property>
<property name="type" value="elephant"></property>
</bean>
<bean id="snake" class="com.caveofprogramming.spring.test.Animal">
<property name="name" value="Bob"></property>
<property name="type" value="snake"></property>
</bean>

now in order to pass List<Animal> to a Jungle bean you write:

<bean id="jungle" class="com.caveofprogramming.spring.test.Jungle">
<property name="animals">
<list>
<ref bean="snake" />
<ref bean="elephant" />
<ref bean="lion" />
</list>
</property>
</bean>

as you see you use the ref tag to add a bean to the list.


No comments:

Post a Comment