Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using dependency injection for instantiating multiple implementations for an interface

 
Swapnil Sonawane
Ranch Hand
Posts: 190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I've a design like below -

In the absence of DatabaseWriter, I'm currently using getBeanNamesForType method to inject the only available bean. But when I have multiple implementations of the interface, I'm not sure how to do this effectively. Using getBeanNamesForType and iterating over the retrieved list doesn't really look like an elegant way. I want to avoid hard-coding the bean names inside the someMethod(). I'm sure this must be a very common use-case today. What's the standard way of solving this using spring?

Thanks,
Swapnil
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could autowire by type.
 
Swapnil Sonawane
Ranch Hand
Posts: 190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But isn't it that I will have two matching beans for the interface type defined in the class which is going to make use of it eventually. I mean there will be two beans compatible with the interface type, which throws UnsatisfiedDependencyException according to the documentation. Please correct me if I'm wrong.

Thanks,
Swapnil
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I mean is you'll need to use a collection class (or array) to accept more than one bean. You can auto-wire by type to get all the beans of that type in the collection type.
 
Atul Kotwale
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, swapnil you are right, autowire byType allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic