13

I am learning spring but while i tried below it doesn't work but at the place of constructor while I use method then it works why? Is there any specific reason behind it? My question is why spring designers decided not to allow @Qualifier above constructor but above method?

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Employee {
    private Company comp;
    @Autowired
    @Qualifier(value="beanId")
    private Employee(Company comp) {
        this.comp=comp;
    }
    public Company getComp() {
        return comp;
    }
}

@Qualifier within argument works.. say below works it's ok

private Employee(@Qualifier(value="beanId") Company comp) {
        this.comp=comp;
}

But @Qualifier works fine above method like below why?

@Qualifier(value="beanId")
private void getEmpDetails(Company comp) {
        this.comp=comp;
}
PANKAJ DUBEY
  • 173
  • 1
  • 1
  • 8
  • 4
    If you have multiple parameters, which parameter should the `@Qualifier` apply to? – Sotirios Delimanolis Feb 20 '17 at 17:37
  • Ok then why below works I mean why it works for method please let me know If I am missing anything obvious Thanks :) @Qualifier(value="beanId") private void abc(Company comp) { this.comp=comp; } – PANKAJ DUBEY Feb 20 '17 at 17:42
  • Below what? What are you referring to? – Sotirios Delimanolis Feb 20 '17 at 17:43
  • @SotiriosDelimanolis I edited my question above, please have a look – PANKAJ DUBEY Feb 20 '17 at 17:50
  • I'm a bit surprised it's working on the method as according to the [documentation](http://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/beans/factory/annotation/Qualifier.html) that's not a valid target. – DavidS Feb 20 '17 at 18:05
  • 2
    It is a valid target in the newer API. Note that your link is for version 2.5.x, and Spring is currently on version 5.0.0 – stelar7 Feb 20 '17 at 18:06

1 Answers1

7

Yes for constructors you can not use @Qualifier as you use it for other methods.
@Qualifier annotation can be used only for the constructor arguments.

See this offcial article for more reference.

Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88