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


问题内容

我正在尝试在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>

我尚未在文档中找到如何执行此操作的示例或其他内容。另外,对于如何实现我想做的更好的方法,您有任何建议,请告诉我:)。


问题答案:

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