'How to write a spring bean with a constructor that contains a list?
I have a list as follows:
ArrayList<DiameterMessageHandler> handlers = new ArrayList<>();
handlers.add(new AARHandler());
handlers.add(new CERHandler());
handlers.add(new PPAHandler());
handlers.add(new STRHandler());
handlers.add(new DWRHandler());
I am wondering how to create a spring bean that takes handlers as one of its arguments, i.e. is it possible to do this in the applicationContext.xml - Do I have to create separate beans for the list and each of the handlers(AARHandler etc) first? Here is my applicationContext.xml
<bean id="DiameterClient" class="com.rory.ptspsim.diameterclient.DiameterClient" scope="singleton" init-method="start">
<constructor-arg type="java.lang.String" index="0"><value>${pcca.host}</value></constructor-arg>
<constructor-arg index="1">WHAT GOES HERE?</constructor-arg>
</bean>
Solution 1:[1]
I think the most appropriate way to do that is:
<bean id="DiameterClient" class="com.rory.ptspsim.diameterclient.DiameterClient" scope="singleton" init-method="start">
<constructor-arg type="java.lang.String" index="0"><value>${pcca.host}</value></constructor-arg>
<constructor-arg index="1">
<list>
<ref bean="aarHandler" />
<ref bean="cerHandler" />
<ref bean="ppaHandler" />
<ref bean="strHandler" />
<ref bean="dwrHandler" />
</list>
</constructor>
</bean>
Solution 2:[2]
If you want all available Handlers, Spring will also collect them for you via Autowiring:
public DiameterClient(@Autowired List<DiameterMessageHandler> handlers){
this.handlers = handlers;
}
Now Spring will inject a List of all available Handlers.
Solution 3:[3]
<bean id="DiameterClient" class="com.rory.ptspsim.diameterclient.DiameterClient" scope="singleton" init-method="start">
<constructor-arg type="java.lang.String" index="0"><value>${pcca.host}</value></constructor-arg>
<constructor-arg index="1">
<list>
<bean class="AARHandler"/>
<bean class="CERHandler"/>
</list>
</constructor-arg>
</bean>
Solution 4:[4]
<list> <ref bean="handler1" /> <ref bean="handler2" /> <ref bean="handler3" /> <ref bean="handler4" /> <ref bean="handler5" /> </list> <bean id="handler1" class="AARHandler"/> <bean id="handler2" class="CERHandler"/> <bean id="handler3" class="PPAHandler"/> <bean id="handler4" class="STRHandler"/> <bean id="handler5" class="DWRHandler"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sean Patrick Floyd |
| Solution 3 | Adisesha |
| Solution 4 | Paul Whelan |
