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

我无法更改类配置器。

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

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

变成一颗豆子。

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

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

有人能帮我一下吗?


当前回答

这是如何在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>

其他回答

导入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指定列表实现类。

作为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);
    }
}

这是如何在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>

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

使用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>