我可以使用spring @Autowired依赖项注入来构建一个类的多个实例吗?

时间:2019-10-12 18:47:23

标签: java spring dependency-injection autowired

我有一个vaadin UI类,其构造函数带有2个参数。它用一些字段构建一条简单的线,显示数据。在另一个(父)UI中,我想多次嵌入第一个UI(子),具体取决于父中加载的某些数据。所以现在我有两个问题:

  1. 我可以使用springs @Autowired批注将子UI的多个实例注入父级吗?如果是,该怎么办?
  2. 如何将参数传递给@Autowired子类的构造函数?

我已经发现,必须使用@Autowired注释子类的构造函数。

我的带有构造函数的子UI类(用@Autowired注释)

public class ChildUI {

   private String arg1;
   private String arg2;

   @Autowired
   public ChildUI(String arg1, String arg2){
      this.arg1 = arg1;
      this.arg2 = arg2;
   }

}

在我的父类中,我想做这样的事情(personList是从数据库加载的):

public class ParentUI {

   ...
   for(Person p : personList){
      //inject instance of ChildUI here and pass p.getLastName() to arg1 and p.getFirstName() to arg2
   }
   ...

}

我搜索了一段时间,但没有真正找到想要的东西。也许我只是不知道要搜索哪些关键字。也许有人可以尝试解释该怎么做?

2 个答案:

答案 0 :(得分:1)

只需像平常一样创建ChildUI

  for(Person p : personList){
     ChildUI someChild=nChildUI(p.getLastName(),m.getFirstName());
   }
   ...

并使用someChild

或者如果ChildUI注入了其他一些依赖项-首先将其设置为原型范围,然后

    @Autowire
    private ApplicationContext ctx;
....
      for(Person p : personList){
         ChildUI someChild=ctx.getBean(ChildUI.class,p.getLastName(),m.getFirstName());
       }

答案 1 :(得分:1)

我不确定我是否完全理解您的要求,所以请告诉我这是否不是您的意思。

创建childUI的多个实例:这很简单,在配置类中创建多个bean:

| counter |
| ------- |
| 2       |

多个实例注入到另一个bean:如果自动装配一组(或列表)您的bean类型,则该实例的所有实例都将注入到它:

@Configuration
public class ApplicationConfiguration {

  @Bean
  public ChildUI firstBean(){
    return new ChildUI(arg1,arg2);
  }

  @Bean
  public ChildUI secondBean(){
    return new ChildUI(otherArg1,otherArg2);
  }

  @Bean
  public ChildUI thirdBean(){
    return new ChildUI(arg1,arg2);
  }
}