Is there any difference between using @Qualifier("beanName") and @Component("beanName") ?
If not, is there a preferred approach?
- 887
- 5
- 14
- 27
2 Answers
Generally, you use @Component("beanName") on the component, You use @Qualifier("beanName") on a class you are autowiring. Ex
@Component("myComponent1")
public class MyComponent1 implements MyComponent {
....
}
@Component("myComponent2")
public class MyComponent2 implements MyComponent {
....
}
@Service
public class SomeService implements MyService {
@Qualifier("myComponent1")
private MyComponent myComponent;
...
}
If there is more than one implementation of a bean/component, spring won't know which bean to select, so you need to use a the qualifier to specify which one is correct.
Additionally, you can use @Primary on one of the components, so it is always selected by default.
- 2,820
- 5
- 27
- 40
They are totally two different things , sound like you are compare apple and orange to me.
@Component is used to declare a class as a Spring bean which you cannot do it with @Qualifier.
@Qualifier is intended to help Spring to determine which bean to inject if there are more than 1 eligible bean for that injection. It is normally used with @Autowired which add more constraint on the injection point such that there are only one bean can be injected in it.
- 75,099
- 24
- 129
- 153