Reputation: 1081
Is there any difference between using @Qualifier("beanName")
and @Component("beanName")
?
If not, is there a preferred approach?
Upvotes: 2
Views: 2515
Reputation: 90527
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.
Upvotes: 2
Reputation: 3198
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.
Upvotes: 7