Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @Qualifier("beanName") and @Component("beanName")

Tags:

spring

Is there any difference between using @Qualifier("beanName") and @Component("beanName") ? If not, is there a preferred approach?

like image 721
Kamil Roman Avatar asked Jan 20 '26 10:01

Kamil Roman


1 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.

like image 181
mad_fox Avatar answered Jan 23 '26 01:01

mad_fox