我在应用程序中使用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;
    }

}

其他回答

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

另一种选择是使用JavaConfig。假设所有阶段都已经注册为spring bean,你只需要:

@Autowired
private List<Stage> stages;

spring会自动将它们注入到这个列表中。如果你需要保持秩序(上解不能做到这一点),你可以这样做:

@Configuration
public class MyConfiguration {
  @Autowired
  private Stage1 stage1;

  @Autowired
  private Stage2 stage2;

  @Bean
  public List<Stage> stages() {
    return Lists.newArrayList(stage1, stage2);
  }
}

另一个保持顺序的解决方案是在bean上使用@Order注释。然后list将包含按升序标注值排序的bean。

@Bean
@Order(1)
public Stage stage1() {
    return new Stage1();
}

@Bean
@Order(2)
public Stage stage2() {
    return new Stage2();
}
 <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)

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

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

<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;
    }

}