简体   繁体   中英

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

I have a vaadin UI class with a constructor taking 2 arguments. It builds a simple line with some fields, showing data. In another (parent) UI, I want to embed that first UI (child) multiple times, depending on some data loaded in the parent. So now I have two questions:

  1. Can I use springs @Autowired annotation to inject multiple instances of my child UI to the parent? If yes, how do I do this?
  2. How do I pass arguments to the constructor of my @Autowired child class?

I already found out, that I must annotate the constructor of my child class with @Autowired .

My child UI class with constructor (annotated with @Autowired )

public class ChildUI {

   private String arg1;
   private String arg2;

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

}

In my parent class, I want to do something like this (personList is loaded from database):

public class ParentUI {

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

}

I googled for a while but I did not really find what I was looking for. Maybe I just don't know what keywords to search for. Can maybe someone try to explain what to do?

Just create ChildUI like your normally would

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

and do something with someChild

Or if ChildUI have some other dependencies injected - first make it prototype scoped, then

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

I'm not sure I completely understand what you ask, so let me know if that's not what you meant.

Creating multiple instances of your childUI: This is simple, create multiple beans in your configuration class:

@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);
  }
}

multiple instances injected to other bean: If you autowire a set (or list) of the type of your bean, all instances of it will be injected to it:

public class ParentUI {

  private final Set<ChildUI> children;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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