Monday, January 13, 2014

Spring Course: V18 Arbitrary Map as Bean Properties

lets say we have the following class:

public class Jungle {
private Map<String, Animal> animals = new HashMap<String, Animal>();
public void setAnimals(Map<String, Animal> animals) {
this.animals = animals;
}
.....
}

as you can see setAnimals has Map<String,Animal> as input, where Animal is another class.

in order to set this value you write:

<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>

<bean id="jungle" class="com.caveofprogramming.spring.test.Jungle">
<property name="animals">
<map>
<entry key="lion" value-ref="lion"></entry>
<entry key="elephant" value-ref="elephant"></entry>
<entry key="snake" value-ref="snake"></entry>
</map>
</property>
</bean>

as you can see we use <map> in order to set this value, in addition we use value-ref to reference a bean ( you can also use key-ref if the key is a bean).

remember that in the previous tutorial we used <props> to set a Map<String,String> value.

No comments:

Post a Comment