簡體   English   中英

我可以使用 spring @Autowired 依賴注入來構建 class 的多個實例嗎?

[英]Can I use spring @Autowired dependency injection to build multiple instances of a class?

我有一個帶有 2 個 arguments 的構造函數的 vaadin UI class。 它用一些字段構建了一條簡單的線,顯示數據。 在另一個(父) UI 中,我想多次嵌入第一個 UI(子),具體取決於父級中加載的一些數據。 所以現在我有兩個問題:

  1. 我可以使用 springs @Autowired注釋將我的子 UI 的多個實例注入父級嗎? 如果是,我該怎么做?
  2. 如何將 arguments 傳遞給我的@Autowired子 class 的構造函數?

我已經發現,我必須用@Autowired注釋我的孩子 class 的構造函數。

我的孩子 UI class 帶有構造函數(用@Autowired注釋)

public class ChildUI {

   private String arg1;
   private String arg2;

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

}

在我的父母 class 中,我想做這樣的事情(personList 是從數據庫加載的):

public class ParentUI {

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

}

我用谷歌搜索了一段時間,但我並沒有真正找到我想要的東西。 也許我只是不知道要搜索什么關鍵字。 也許有人可以嘗試解釋該怎么做?

像往常一樣創建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());
       }

我不確定我是否完全理解你的要求,所以如果這不是你的意思,請告訴我。

創建 childUI 的多個實例:這很簡單,在配置 class 中創建多個 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);
  }
}

注入其他 bean 的多個實例:如果自動裝配 bean 類型的集合(或列表),它的所有實例都將注入它:

public class ParentUI {

  private final Set<ChildUI> children;

  @Autowired
  public ParentUI(Set<ChildUI> children) {
    this.childern = children;//this will contain all three beans
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM