How to define a List bean in Spring?

I'm using Spring to define stages in my application. It's configured that the necessary class (here called Configurator ) is injected with the stages.
Now I need the List of Stages in another class, named LoginBean . The Configurator doesn't offer access to his List of Stages.

I cannot change the class Configurator .

My Idea:
Define a new bean called Stages and inject it to Configurator and LoginBean . My problem with this idea is that I don't know how to transform this property:

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

into a bean.

Something like this does not work:

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

Can anybody help me with this?


Import the spring util namespace. Then you can define a list bean as follows:

<?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>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class .


以下是一种方法:

<bean id="stage1" class="Stageclass"/>
<bean id="stage2" class="Stageclass"/>

<bean id="stages" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="stage1" />
            <ref bean="stage2" />                
        </list>
    </constructor-arg>
</bean>

Another option is to use JavaConfig. Assuming that all stages are already registered as spring beans you just have to:

@Autowired
private List<Stage> stages;

and spring will automatically inject them into this list. If you need to preserve order (upper solution doesn't do that) you can do it in that way:

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

  @Autowired
  private Stage2 stage2;

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

The other solution to preserve order is use a @Order annotation on beans. Then list will contain beans ordered by ascending annotation value.

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

@Bean
@Order(2)
public Stage stage2() {
    return new Stage2();
}
链接地址: http://www.djcxy.com/p/39158.html

上一篇: Spring Webflow + Spring MVC:Java注释中的Action Bean

下一篇: 如何在Spring中定义一个List bean?