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

我无法更改类配置器。

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

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

变成一颗豆子。

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

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

有人能帮我一下吗?


当前回答

另一种选择是使用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();
}

其他回答

这是如何在Spring的某些属性中注入set:

<bean id="process"
      class="biz.bsoft.processing">
    <property name="stages">
        <set value-type="biz.bsoft.AbstractStage">
            <ref bean="stageReady"/>
            <ref bean="stageSteady"/>
            <ref bean="stageGo"/>
        </set>
    </property>
</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();
}

使用util:list中的list-class属性创建任何特定类型的独立列表。例如,如果你想创建类型为ArrayList的列表:

<util:list id="namesList" list-class="java.util.ArrayList" value-type="java.lang.String">
  <value>Abhay</value>
  <value>ankit</value>
  <value>Akshansh</value>
  <value>Db</value>
</util:list>

或者如果你想创建一个LinkedList类型的列表,那么:

<util:list id="namesList" list-class="java.util.LinkedList" value-type="java.lang.String">
  <value>Abhay</value>
  <value>ankit</value>
  <value>Akshansh</value>
  <value>Db</value>
</util:list>

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

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

作为Jakub回答的补充,如果你计划使用JavaConfig,你也可以这样自动装配:

import com.google.common.collect.Lists;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

<...>

@Configuration
public class MyConfiguration {

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