Reputation: 1825
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>
Upvotes: 24
Views: 54659
Reputation: 381
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>
Upvotes: 8
Reputation: 299208
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.
See Spring Reference 4.9.2: @Autowired
Upvotes: 7
Reputation: 5258
<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>
Upvotes: 2
Reputation: 20336
Probably you want all these handlers be Spring beans too. This is the configuration:
<bean id="DiameterClient" class="com.rory.ptspsim.diameterclient.DiameterClient" init-method="start">
<constructor-arg value="${pcca.host}" />
<constructor-arg>
<list>
<ref bean="aarHandler" />
...
</list>
</constructor-arg>
</bean>
<bean id="aarHandler" class="com.rory.ptspsim.diameterclient.AARHandler" />
Upvotes: 43
Reputation: 16799
<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"/>
Upvotes: 1