我在应用程序中使用Spring定义阶段。它被配置为将必要的类(这里称为Configurator)注入到阶段中。 现在我需要另一个名为LoginBean的类中的阶段列表。配置器不提供对他的阶段列表的访问。

我无法更改类配置器。

我的想法: 定义一个名为Stages的新bean,并将其注入到Configurator和LoginBean。 我对这个想法的问题是,我不知道如何转换这个属性:

<property ...>
  <list>
    <bean ... >...</bean>
    <bean ... >...</bean>
    <bean ... >...</bean>
  </list>
</property>

变成一颗豆子。

像这样的东西是行不通的:

<bean id="stages" class="java.util.ArrayList">

有人能帮我一下吗?


当前回答

<bean id="someBean"
      class="com.somePackage.SomeClass">
    <property name="myList">
        <list value-type="com.somePackage.TypeForList">
            <ref bean="someBeanInTheList"/>
            <ref bean="someOtherBeanInTheList"/>
            <ref bean="someThirdBeanInTheList"/>
        </list>
    </property>
</bean>

在SomeClass中:

class SomeClass {

    List<TypeForList> myList;

    @Required
    public void setMyList(List<TypeForList> myList) {
        this.myList = myList;
    }

}

其他回答

Stacker提出了一个很好的答案,我会更进一步,让它更动态,并使用Spring 3 EL Expression。

<bean id="listBean" class="java.util.ArrayList">
        <constructor-arg>
            <value>#{springDAOBean.getGenericListFoo()}</value>
        </constructor-arg>
</bean>

我试图弄清楚如何用util:列表做到这一点,但由于转换错误无法让它工作。

使用util名称空间,您将能够在应用程序上下文中将该列表注册为bean。然后可以重用该列表,将其注入到其他bean定义中。

我认为您可能在寻找org.springframework.beans.factory.config.ListFactoryBean。

声明一个ListFactoryBean实例,提供要实例化的列表作为属性,其值为<list>元素,并为bean提供一个id属性。然后,每次在其他bean声明中使用已声明的id作为ref或类似的引用时,列表的一个新副本就会实例化。您还可以指定要使用的List类。

导入spring util命名空间。然后你可以定义一个列表bean,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

value-type是要使用的泛型类型,是可选的。您还可以使用属性list-class指定列表实现类。

 <bean id="student1" class="com.spring.assin2.Student">  
<property name="name" value="ram"></property>  
<property name="id" value="1"></property> 
<property name="listTest">
        <list value-type="java.util.List">
            <ref bean="test1"/>
            <ref bean="test2"/>
        </list>
    </property>
</bean>  

然后定义这些bean (test1,test2)