Why do we use qualifiers with @Bean when we can have different names for different beans of the same type (class)?
@Bean
@Qualifier("fooConfig")
public Baz method1() {
}
Isn't the following code more clean?
@Bean("fooConfig")
public Baz method1() {
}
If I create two beans of the same type with different names (using @Bean annotation), then can we inject them specifically using the @Qualifier annotation(can be added on field/constructor parameter/setter) in another bean?
@Bean("fooConfig")
public Baz method1(){
}
@Bean("barConfig")
public Baz method2(){
}
// constructor parameter of a different bean
final @Qualifier("fooConfig") Baz myConfig
If the above is true, then where do we use @Qualifier (with @Bean or @Component) instead of giving the bean a name as shown below?
@Bean
@Qualifier("fooConfig")
public Baz method1(){
}
@Bean
@Qualifier("barConfig")
public Baz method2(){
}
// constructor parameter of a different bean
final @Qualifier("fooConfig") Baz myConfig
For example:
If you will try to inject myComponent somewhere, Spring is smart enough to find the bean above. Becaude there is only one Bean with return type MyCustomComponent. But if there was a couple of methods, that would return MyCustomComponent, then you would have to tell Spring which one to inject with @Qualifier annotation.
SIDENOTE: @Bean annotation by default Spring uses the method name as a bean name. You can also assign other name like @Bean("otherComponent").
This is you interface:
This is your implementation 1:
Your implementation 2:
Now you are injecting it like:
QUESTION! How is Spring supposed to know which class to inject? Test1 or Test2? That's why you tell it with @Qualifier which class.