在Spring bean上下文中声明一个对象数组

时间:2010-08-31 15:53:26

标签: java spring javabeans

我正在尝试在Spring上下文文件中创建一个对象数组,因此我可以将它注入一个声明如下的构造函数:

public RandomGeocodingService(GeocodingService... services) { }

我正在尝试使用<array>标记:

<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 个答案:

答案 0 :(得分:32)

那是因为没有<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>

答案 1 :(得分:6)

Spring可以自动将列表转换为数组[]

查看http://forum.springsource.org/showthread.php?37767-Injecting-String-Array

<bean name="test" class="Test">
   <property name="values" value="hugo,emil"></property>
</bean>

答案 2 :(得分:4)

查看util schema

答案 3 :(得分:0)

我想知道为什么给出最佳答案的用户说...

“那是因为没有<array>这样的东西,只有<list>

我目前正在使用<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>