Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is @Qualifier and when do you need it? @Qualifier क्या है और इसकी ज़रूरत कब पड़ती है?

Answer

When multiple beans of the same type exist in the container, @Autowired alone can't determine which one to inject, causing a NoUniqueBeanDefinitionException. @Qualifier("beanName") resolves the ambiguity by specifying exactly which bean implementation should be wired in, matched against the bean's name or an explicit qualifier value.

An alternative to @Qualifier is marking one implementation with @Primary so it becomes the default choice whenever multiple candidates exist, without needing to qualify every injection point — @Qualifier is preferred when you need to select different implementations at different injection points.

public interface NotificationService { void send(String msg); }

@Service("emailNotification")
public class EmailNotificationService implements NotificationService { ... }

@Service("smsNotification")
public class SmsNotificationService implements NotificationService { ... }

@Service
public class OrderService {
    public OrderService(@Qualifier("emailNotification") NotificationService service) { ... }
}

जब कंटेनर में एक ही टाइप के कई बीन्स मौजूद हों, तो अकेला @Autowired यह तय नहीं कर सकता कि कौन-सा इंजेक्ट करना है, जिससे NoUniqueBeanDefinitionException आता है। @Qualifier("beanName") यह स्पष्ट करके अस्पष्टता हल करता है कि कौन-सा बीन इम्प्लीमेंटेशन वायर किया जाना चाहिए।

@Qualifier का एक विकल्प है एक इम्प्लीमेंटेशन को @Primary से चिह्नित करना ताकि यह डिफ़ॉल्ट विकल्प बन जाए; @Qualifier तब पसंद किया जाता है जब अलग-अलग इंजेक्शन पॉइंट्स पर अलग-अलग इम्प्लीमेंटेशन चुनने की ज़रूरत हो।

@Service
public class OrderService {
    public OrderService(@Qualifier("emailNotification") NotificationService service) { ... }
}

Was this answer clear?