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

2022-09-02 05:31:32

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

我无法在有关如何执行此操作的文档中找到示例或内容。另外,您对实现我正在尝试的更好方法有任何建议,请:)告诉我。


答案 1

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

好消息是,Spring将根据需要在列表和数组之间自动转换,因此将您的数组定义为,Spring将它强制转换为数组。<list>

这应该有效:

<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 id="geocodingService" class="geocoding.RandomGeocodingService">
    <constructor-arg>
       <ref bean="googleGeocodingService"/>
    </constructor-arg>
</bean>

答案 2

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

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

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

推荐