tags:

views:

207

answers:

1

I like constructor injection as it allows me to make injected fields final. I also like annotation driven injection as it simplifies my context.xml. I can mark my contructor with @Autowired and everything works fine, as long as I dont have to 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 an application context with :

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

There should be a way to specify the bean ID on the constructor of the class SomeClass but I cant find it in the documentation. Is it possible ? Or am I dreaming of a solution that does not exist yet ?

Edit

Follwoing Bozho's answer, I modified my class to be :

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

and it works ...

+5  A: 

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

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

Note: In contrast to @Autowired which is applicable to fields, constructors and multi-argument methods (allowing for narrowing through qualifier annotations at the parameter level), @Resource is only supported for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

(below that text is the full example)

Bozho
`@Autowire` is by-name too, but in that case you need to provide setters. But here constructor arguments is preferred, and `@Autowire` will not work if both args are of same type. Hence, the thing can be solved using `@Qualifier`.
Adeel Ansari
clarified the answer.
Bozho
Noticed.......+1
Adeel Ansari