views:

500

answers:

2

Hi,

is there a way to use dependency injection to inject all available implementations of a specific interface in spring?

This is kind of the same thing as asked here for .NET.

Though my aim is to use @Autowired for this:

public class Foo{
  @Autowired
  private IDataCollector[] collectors;
}

Is this supported, would this require hacking or should I preferably use another component where all implementations of IDataCollector register themselve and use that accessor component with autowired instead of the array injection?

A reason I can think of why this may not be implemented per default may be, that it would also inject possible mock implementations where inappropriate. Though I'm still interested wether this is possible or not. :)

+2  A: 

Your example should work fine, as should List<IDataCollector>. Did you give it a try before asking, and found it didn't work?

http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation

It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type.

skaffman
thank you, I just started with my interest in spring, I really should RTFM ;)
subes
There's a lot of M to F'ing R :)
skaffman
+2  A: 

you can inject a List and Spring will convert this for you:

<util:list id="collectors">
  <value>[email protected]</value>
  <value>[email protected]</value>
</util:list>
David Rabinowitz
is this a list specified in the spring xml configuration that gets injected or how can I understand this?
subes
Nope - Spring added some helper configuration in the util namesapce, see here http://static.springsource.org/spring/docs/2.5.6/reference/xsd-config.html
David Rabinowitz