aspose file tools*
The moose likes Spring and the fly likes Using dependency injection for instantiating multiple implementations for an interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Using dependency injection for instantiating multiple implementations for an interface" Watch "Using dependency injection for instantiating multiple implementations for an interface" New topic
Author

Using dependency injection for instantiating multiple implementations for an interface

Swapnil Sonawane
Ranch Hand

Joined: Jan 02, 2008
Posts: 190
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


Swapnil S. Sonawane<br /> <br />B.Tech (Expected May 2009)<br />Computer Science, NIT Durgapur, India<br />SCJA 1.0
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 597

You could autowire by type.


Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
Swapnil Sonawane
Ranch Hand

Joined: Jan 02, 2008
Posts: 190
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

Joined: Feb 08, 2009
Posts: 597

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

Joined: Dec 22, 2011
Posts: 17
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using dependency injection for instantiating multiple implementations for an interface
 
Similar Threads
java does not support multiple inheritance. Is it a limitation to java?
Related to interface.
Observer Example
Interfaces
i really don't understand interfaces....