Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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> 
like image 888
Rory Avatar asked Feb 10 '12 10:02

Rory


People also ask

Can we have constructor in Spring bean?

There are four constructors and one method in this class. We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked.

Can we use @autowired for constructor?

Using @Autowired After enabling annotation injection, we can use autowiring on properties, setters, and constructors.


1 Answers

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" /> 
like image 87
sinuhepop Avatar answered Oct 06 '22 16:10

sinuhepop