2

I have an interface:

public interface EmailSender {

    void send(Locale locale, List<User> recipients, int ticketId);

}

And few different implementations, and I want to autowire a HashMap of them, to have possibility to get concrete realization by class name, but when I write:

@Autowired
private HashMap<String, EmailSender> emailSenders;

I get an exception:

No qualifying bean of type 'java.util.HashMap'

@Autowired
private List<EmailSender> emailSenders;

It is interesting that whet I tried to change HashMap to List all worked fine, do you know how to correctly do that?

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Fairy
  • 509
  • 1
  • 9
  • 27

4 Answers4

4

reposting saw303's comment as an answer so it's easier to find (I almost missed the comment until I reread the OP a second time)

Use a Map instead of a concrete HashMap – saw303 Dec 5 '17 at 19:28

Adam
  • 226
  • 2
  • 11
0

create a class which will extends hashMap and Autowire that class. it will work fine for you.

In list you are actually autowiring EmailSender class unlike string in hashmap.

mark that class as component and autowire that. hopefully, it will work for you. Cheers

Ravat Tailor
  • 1,193
  • 3
  • 20
  • 44
0

I think, you should declare your bean in Configuration class.

@Bean 
public HashMap<String, EmailSender> emailSenders(List<EmailSender> emailSenders){
    HashMap<String, EmailSender> map = new HashMap<>();
    emailSenders.forEach(sender -> map.put(sender.getClass().getName(), sender));
    return map;
}
0

If you define your bean of your own(not collectable) type:

With Spring you can create few beans of same type. But in this case you can't do this:

@Authowire 
private MyBean bean1;

@Authowire 
private MyBean bean2;

But you can do next:

@Authowire 
@Qualifier("firstBean")
private MyBean bean1;

@Authowire 
@Qualifier("firstBean")
private MyBean bean2;

And in same time you can get all instances of you bean, asking for getting list of them

@Authowire 
private List<MyBean> beans;  // all you beans will be here

If you defined your bean of type List or Map of your type:

Also please take a look on https://stackoverflow.com/a/13914052/814304 If you use Spring version lower then 4.3 you need use annotation @Resource if you defined you bean of type Map or List.

iMysak
  • 2,170
  • 1
  • 22
  • 35