在Spring Bean上下文中声明对象数组

20

我正在尝试在Spring上下文文件中创建一个对象数组,以便可以将其注入到这样声明的构造函数中:

public RandomGeocodingService(GeocodingService... services) { }
我正在尝试使用标签:
<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
 <constructor-arg ref="proxy" />
 <constructor-arg value="" />
</bean>

<bean id="geocodingService" class="geocoding.RandomGeocodingService">
    <constructor-arg>
        <array value-type="geocoding.GeocodingService">
            <!-- How do I reference the google geocoding service here? -->
        </array>
    </constructor-arg>
</bean>

我在文档中没有找到如何实现这一点的示例或说明。如果你有任何更好的建议,请告诉我 :)

4个回答

34

那是因为并不存在一个名为 <array> 的东西,只有 <list> 存在。

好消息是Spring会根据需要自动在列表和数组之间进行转换,所以将你的数组定义为一个 <list>,Spring将强制将其转换为数组。

这应该可以工作:

<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
   <constructor-arg ref="proxy" />
   <constructor-arg value="" />
</bean>

<bean id="geocodingService" class="geocoding.RandomGeocodingService">
    <constructor-arg>
        <list>
           <ref bean="googleGeocodingService"/>
        </list>
    </constructor-arg>
</bean>

如果需要的话,Spring也会将单个bean强制转换为列表:

<bean id="geocodingService" class="geocoding.RandomGeocodingService">
    <constructor-arg>
       <ref bean="googleGeocodingService"/>
    </constructor-arg>
</bean>

8

5

5
我实际上使用<array>标签将对象数组注入到bean中,它能够正常工作。
请看以下代码...
    <bean id="song1" class="mx.com.company.songs.Song">
        <property name="name" value="Have you ever seen the rain?"/>        
    </bean>
    
    <bean id="song2" class="mx.com.company.songs.Song">
        <property name="name" value="La bamba"/>      
    </bean>

    <bean id="guitarPlayer" class="mx.com.company.musician.GuitarPlayer">
        <property name="songs">
            <array>
                <ref bean="song1"/>
                <ref bean="song2"/>
            </array>
        </property>
    </bean> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接