Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Spring XML configuration to set a bean property with list of all beans of a certain type?

Tags:

java

spring

I have the following XML configuration:

<bean id="bean1" class="Simple"/>
<bean id="bean2" class="Simple"/>

<bean id="tasks" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="bean1" />
            <ref bean="bean2" />                
        </list>
    </constructor-arg>
</bean>

<bean id="list" class="Comp">
    <property name="tasks" ref="tasks"/>
</bean>

The "tasks" contains all beans of type Simple. The problem with this is that I might forget to add a Simple bean I've configured to the list.

I could do this programatically using

Map map = context.getBeansOfType(Simple.class);

and setting the list bean with the beans retrieved.

Is there any way of doing this using just XML configuration?

like image 680
David Resnick Avatar asked Jun 03 '09 07:06

David Resnick


1 Answers

Your context file should like this:

<bean id="bean1" class="Simple"/>
<bean id="bean2" class="Simple"/>

<bean id="list" class="Comp" autowire="byType"/>

Note the autowire="byType" addition, and the autowiring documentation.

like image 156
Robert Munteanu Avatar answered Sep 28 '22 04:09

Robert Munteanu