Reputation: 341
Is there a way to iterate list or map in spring? I am not able to find any references for this online.
This is what I defined-
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<util:list id="myList" value-type="java.lang.String">
<value>foo</value>
<value>bar</value>
</util:list>
<bean id="bean1" class="com.StaticClass" factory-method="createObject">
<constructor-arg value="foo" />
</bean>
<bean id="bean2" class="com.StaticClass" factory-method="createObject">
<constructor-arg value="bar" />
</bean>
<bean id="myMap" class="java.util.HashMap">
<constructor-arg index="0" type="java.util.Map">
<map key-type="java.lang.Integer" value-type="java.lang.Float">
<entry key="foo" value-ref=bean1 />
<entry key="bar" value-ref=bean2 />
</map>
</constructor-arg>
</bean>
Instead of creating multiple bean objects, I want to iterate over this list and create a map, using following logic-
for (String m : myList) {
myMap.put(m, MyStaticFactory.createObject(m));
}
Can I do this in Spring?
Upvotes: 0
Views: 3510
Reputation: 21866
How about using spring @Configuration (see explanation in this link) instead of spring XML?
@Configuration
public class MySpringContext {
@Bean(name="myMap")
public Map<String, StaticClass> getMyMapBean() {
// I'm not sure where you create 'm' but if that's a bean you can inject it to the class and use it.
for (String m : myList) {
myMap.put(m, MyStaticFactory.createObject(m));
}
}
}
@Configuration classes are a way to define your beans programatically instead of XMLs which gives you much more flexibility to do whatever you want.
Upvotes: 1
Reputation: 40510
Something like this maybe:
public class MyMapBean extends HashMap {
public MyMapBean(List<String> beanNames) {
for(name: beanNames) put(name, MyStaticFactory.createObject(name));
}
}
and then in application context:
<bean id="myMap" class="MyMapBean">
<constructor-arg index="0" value-ref="myList" />
</bean>
Upvotes: 0