How to write a spring bean with a constructor that contains a list?

Rory picture Rory · Feb 10, 2012 · Viewed 47.2k times · Source

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>

Answer

sinuhepop picture sinuhepop · Feb 10, 2012

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