在Spring bean上下文中声明一个对象数组 [英] Declaring an array of objects in a Spring bean context
问题描述
我正在尝试在Spring上下文文件中创建一个对象数组,因此我可以将它注入一个声明如下的构造函数:
I'm trying to create an array of objects in a Spring context file so I can inject it to a constructor that's declared like this:
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>
我无法在文档中找到有关如何操作的示例或内容这个。另外,你有任何建议可以更好地实现我想要做的事情,请告诉我:)。
I haven't been able to find an example or something in the in the documentation on how to do this. Also, you have any suggestions for a better way of acheiving what I'm trying to do, please let me know :).
推荐答案
<那是因为没有< array>
这样的东西,只有< list>
。
好消息是Spring会根据需要在列表和数组之间自动转换,因此将数组定义为< list>
,Spring会将它强制转换为数组。
The good news is that Spring will auto-convert between lists and arrays as required, so defined your array as a <list>
, and Spring will be coerce it into an array for you.
这应该有效:
<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强制转换为列表:
Spring will also coerce a single bean into a list, if required:
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<ref bean="googleGeocodingService"/>
</constructor-arg>
</bean>
这篇关于在Spring bean上下文中声明一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!