Reputation: 18865
I have what seems to be a simple problem, as stated in the title. Here is the kind of class I have :
public class Foo {
@Autowired
public Foo(@Qualifier("bar") Set<String> bar) {
// ...
}
}
Which I try to run with the following spring context :
<context:annotation-config />
<util:set id="bar">
<value>tata</value>
<value>titi</value>
<value>toto</value>
</util:set>
<bean id="foo" class="Foo" />
This fails to run with :
No matching bean of type [java.lang.String] found for dependency [collection of java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=bar)}
Note that if I add other parameters to my constructor, it works fine. If I use setter injection, it works fine. I'm sure I miss something obvious ... do you know what ?
Upvotes: 22
Views: 12881
Reputation: 10759
I had this same problem and was inspired by @rembisz's answer. That answer didn't work on my version of Spring (4.1.3). When I checked the SpEL documentation on bean references, I found a different SpEL syntax to express bean references in autowired values that worked for me - @beanname
. As such, the following code worked for me:
public class Foo {
@Autowired
public Foo(@Value("#{@bar}") Set<String> bar) {
// ...
}
}
Upvotes: 2
Reputation: 12880
As others stated it is impossible to use @Autowired for Strings and collections of String. You can use @Value with spring EL here assuming you have spring in version 3:
public class Foo { @Autowired public Foo(@Value("#{bar}") Set<String> bar) { // ... } }
Upvotes: 5
Reputation: 9013
Autowiring collections is not possible using the @Autowired
annotation. An autowired collection means "to provide all beans of a particular type". Using the JSR-250 @Resource
annotation, you can declare that you want a resource injected by its name, not its type. Or you inject the dependency explicitly.
[...] beans which are themselves defined as a collection or map type cannot be injected via
@Autowired
since type matching is not properly applicable to them. Use@Resource
for such beans, referring to the specific collection/map bean by unique name.
See the Spring documentation for more details.
Upvotes: 23
Reputation: 403531
I think this is because Spring interprets the autowiring of a collection as "give me all beans of type String
", rather than "give me the bean which is a collection of String
". The error message supports that idea.
I don't think you can use autowiring for this. Short of manually wiring it up in the XML, the best I can suggest is:
public class Foo {
private @Resource Set<String> bar;
}
Upvotes: 2