Spring - enter 2 beans of the same type

I like constructor-based injection, as it allows me to enter final input fields. I also like nesting with annotation as it simplifies my context.xml . I can mark my @Autowired constructor, and everything works fine if I don't have two parameters of the same type. For example, I have a class:

 @Component public class SomeClass { @Autowired(required=true) public SomeClass(OtherClass bean1, OtherClass bean2) { … } } 

and application context with:

 <bean id="bean1" class="OtherClass" /> <bean id="bean2" class="OtherClass" /> 

There should be a way to specify the bean identifier in the constructor of the SomeClass class, but I cannot find it in the documentation. Is it possible, or am I dreaming of a solution that does not yet exist?

+45
java spring
Jan 28 '10 at
source share
1 answer

@Autowired is by type (in this case); use @Qualifier to auto-detect by name, following the example from spring docs :

 public SomeClass( @Qualifier("bean1") OtherClass bean1, @Qualifier("bean2") OtherClass bean2) { ... } 

Note. Unlike @Autowired, which is applicable to fields, constructors, and methods with multiple arguments (allowing narrowing through classifier annotations at the parameter level), @Resource is supported only for fields and bean methods for setting properties with a single argument. As a result, stick to qualifiers if your goal of implementation is a constructor or method with several arguments.

(below this text is a complete example)

+67
Jan 28 '10 at 10:11
source share



All Articles