简体   繁体   English

如何在 Spring 中定义 List bean?

[英]How to define a List bean in Spring?

I'm using Spring to define stages in my application.我正在使用 Spring 在我的应用程序中定义阶段。 It's configured that the necessary class (here called Configurator ) is injected with the stages.它被配置为必要的类(这里称为Configurator )注入了阶段。
Now I need the List of Stages in another class, named LoginBean .现在我需要另一个名为LoginBean类中的阶段列表。 The Configurator doesn't offer access to his List of Stages. Configurator器不提供对他的阶段列表的访问。

I cannot change the class Configurator .我无法更改Configurator类。

My Idea:我的点子:
Define a new bean called Stages and inject it to Configurator and LoginBean .定义一个名为 Stages 的新 bean 并将其注入ConfiguratorLoginBean 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.导入 spring util 命名空间。 Then you can define a list bean as follows:然后你可以定义一个列表 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>

The value-type is the generics type to be used, and is optional. value-type 是要使用的泛型类型,并且是可选的。 You can also specify the list implementation class using the attribute list-class .您还可以使用属性list-class指定列表实现list-class

Here is one method:这是一种方法:

<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.另一种选择是使用 JavaConfig。 Assuming that all stages are already registered as spring beans you just have to:假设所有阶段都已经注册为 spring bean,你只需要:

@Autowired
private List<Stage> stages;

and spring will automatically inject them into this list. spring 会自动将它们注入到这个列表中。 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.另一种保持顺序的解决方案是在 bean 上使用@Order注释。 Then list will contain beans ordered by ascending annotation value.然后列表将包含按升序注释值排序的 bean。

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

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

And in SomeClass:在 SomeClass 中:

class SomeClass {

    List<TypeForList> myList;

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

}

Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression. Stacker 提出了一个很好的答案,我会更进一步使其更具动态性并使用 Spring 3 EL Expression。

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

I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors.我试图弄清楚如何使用 util:list 执行此操作,但由于转换错误而无法使其正常工作。

I think you may be looking for org.springframework.beans.factory.config.ListFactoryBean .我想你可能正在寻找org.springframework.beans.factory.config.ListFactoryBean

You declare a ListFactoryBean instance, providing the list to be instantiated as a property withe a <list> element as its value, and give the bean an id attribute.您声明一个 ListFactoryBean 实例,提供要实例化的列表作为属性,并以<list>元素作为其值,并为 bean 提供一个id属性。 Then, each time you use the declared id as a ref or similar in some other bean declaration, a new copy of the list is instantiated.然后,每次在其他 bean 声明中使用声明的id作为ref或类似内容时,都会实例化列表的新副本。 You can also specify the List class to be used.您还可以指定要使用的List类。

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

define those beans(test1,test2) afterwards :)之后定义这些 bean(test1,test2) :)

Use the util namespace, you will be able to register the list as a bean in your application context.使用 util 命名空间,您将能够将列表注册为应用程序上下文中的 bean。 You can then reuse the list to inject it in other bean definitions.然后,您可以重用该列表以将其注入其他 bean 定义中。

As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:作为 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);
    }
}

You just remove id out of beans inside <list> tag.您只需从<list>标签内的 bean 中删除id Like this:像这样:

<property name="listStaff">
  <list>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jonh"/>
        <constructor-arg name="age" value = "30"/>
    </bean>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jam"/>
        <constructor-arg name="age" value = "21"/>
    </bean>
  </list>
</property>

Inject list of strings.注入字符串列表。

Suppose you have Countries model class that take list of strings like below.假设您有一个采用如下字符串列表的国家模型类。

public class Countries {
    private List<String> countries;

    public List<String> getCountries() {
        return countries;
    }   

    public void setCountries(List<String> countries) {
        this.countries = countries;
    }

}

Following xml definition define a bean and inject list of countries.以下 xml 定义定义一个 bean 并注入国家/地区列表。

<bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
   <property name="countries">
      <list>
         <value>Iceland</value>
         <value>India</value>
         <value>Sri Lanka</value>
         <value>Russia</value>
      </list>
   </property>
</bean>

Reference link参考链接

Inject list of Pojos注入 Pojo 列表

Suppose if you have model class like below.假设您有如下所示的模型类。

public class Country {
    private String name;
    private String capital;
    .....
    .....
 }

public class Countries {
    private List<Country> favoriteCountries;

    public List<Country> getFavoriteCountries() {
        return favoriteCountries;
    }

    public void setFavoriteCountries(List<Country> favoriteCountries) {
        this.favoriteCountries = favoriteCountries;
    }

}

Bean Definitions.豆定义。

 <bean id="india" class="com.sample.pojo.Country">
  <property name="name" value="India" />
  <property name="capital" value="New Delhi" />
 </bean>

 <bean id="russia" class="com.sample.pojo.Country">
  <property name="name" value="Russia" />
  <property name="capital" value="Moscow" />
 </bean>


 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="favoriteCountries">
   <list>
    <ref bean="india" />
    <ref bean="russia" />
   </list>
  </property>
 </bean>

Reference Link .参考链接

And this is how to inject set in some property in Spring:这是如何在 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>

Use list-class attribute in util:list to make a standalone list of any particular type.在 util:list 中使用 list-class 属性来制作任何特定类型的独立列表。 for example if you want to make list of type ArrayList:例如,如果您想制作 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>

or if you want to make a list of type LinkedList then :或者,如果您想制作 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM