@Qualifier annotation in Spring?@Qualifier annotation is used to resolve ambiguity when multiple beans of the same type exist. It tells Spring exactly which bean should be autowired when there are several matching candidates for dependency injection.@Qualifier and @Primary in Spring?@Primary is used to indicate which bean should be preferred when multiple beans of the same type exist. If no @Qualifier is specified, Spring will inject the primary bean by default. On the other hand, @Qualifier is more explicit and allows you to specify exactly which bean to inject regardless of whether @Primary is used.@Qualifier with constructor injection?You can use @Qualifier with constructor injection by annotating the parameter with it:
@Service
public class MyService {
private MyInterface myInterface;
@Autowired
public MyService(@Qualifier("class1") MyInterface myInterface) {
this.myInterface = myInterface;
}
}
@Qualifier with a collection of beans?Yes, you can use @Qualifier with collections like List or Set when injecting multiple beans of the same type. You can also use @Qualifier on the individual elements if necessary.
@Autowired
@Qualifier("specificBean")
private List<MyInterface> myInterfaces;
@Qualifier interact with @Primary?@Primary and @Qualifier are used, @Qualifier takes precedence over @Primary. If you specify a @Qualifier, it will always choose the qualified bean, regardless of which bean is marked as @Primary.@Qualifier be used with custom annotations? How?Yes, you can create custom qualifiers by creating your own annotations and using @Qualifier within them. This is helpful when you need more semantic or domain-specific annotations.
@Qualifier
@Retention(RUNTIME)
@Target({ FIELD, METHOD, PARAMETER, TYPE })
public @interface CustomQualifier {
}
@Qualifier with a bean that doesn't exist?@Qualifier with a bean name that doesn’t exist, Spring will throw a NoSuchBeanDefinitionException. It indicates that Spring couldn’t find a matching bean for the qualifier provided.@Qualifier be used with primitive types or @Value injections?@Qualifier is specifically designed for resolving bean injection ambiguities. For primitive types and properties injection (e.g., String, int), @Value should be used.@Qualifier with multiple constructor arguments?When a constructor has multiple arguments of the same type or different beans need to be injected, @Qualifier can be used on each parameter to ensure the correct bean is injected.
public MyService(@Qualifier("bean1") MyInterface bean1, @Qualifier("bean2") MyInterface bean2) {
this.bean1 = bean1;
this.bean2 = bean2;
}