# @Autowired, @Qualifier and @Primary

> You have two implementations of the same interface in your Spring context. How does Spring decide which one to inject, and how do you control it?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-autowired-qualifier-primary
Last updated: 2026-11-28

Difficulty: Beginner

## Question

You have two implementations of the same interface in your Spring context. How does Spring decide which one to inject, and how do you control it?

## Answer

Here is a situation you will hit within your first month on a real project. You define a NotificationSender interface, then write EmailSender and SmsSender implementations, both annotated @Service. Now some class asks for a NotificationSender, and the application refuses to start with NoUniqueBeanDefinitionException. Spring found two candidates and does not want to guess. Understanding how it resolves such ambiguity is exactly what this question tests.

@Autowired tells Spring to inject a dependency. Resolution goes in steps. First it matches by type. If exactly one bean matches, done. If several match, it looks for a bean marked @Primary. If none is primary, it looks for a @Qualifier on the injection point. Finally, as a fallback, it compares the parameter or field name with the bean names, so a parameter called emailSender can match a bean named emailSender. If all of that fails, you get the exception.

@Primary is the default-winner approach. You mark one implementation as primary, and it is chosen whenever there is no more specific instruction. It is ideal when one implementation is the normal choice and others are special cases. @Qualifier is the explicit-choice approach. You give the bean a name, for example @Service("smsSender"), and at the injection point you write @Qualifier("smsSender"). Qualifier overrides primary, because it is more specific. A custom qualifier annotation is also possible, which is neat when you want a type-safe label like @Sms instead of a raw string.

There is another elegant option when you actually want all implementations: inject a List<NotificationSender> or a Map<String, NotificationSender>. Spring gives you every bean of the type, and with the map the keys are bean names. This is the base of the strategy pattern in Spring: a factory that picks the sender by a runtime key without any if-else on concrete classes.

On the @Autowired details: with constructor injection and a single constructor it is optional. The required attribute defaults to true, so a missing dependency fails startup; set required = false or use Optional or @Nullable for optional dependencies. Also note that @Autowired on a field of a type that has zero beans produces NoSuchBeanDefinitionException, so check the classpath and component scan first when you see it.

A last interviewer favourite is @Resource versus @Autowired. @Resource is a JSR-250 annotation that resolves primarily by name, then by type, while @Autowired resolves by type first. Also mention that @Inject is the JSR-330 equivalent of @Autowired. In practice, prefer constructor injection with @Qualifier on the parameter when needed, and avoid ambiguity by design where you can.

## Code examples

### Resolving ambiguity three ways

```
public interface NotificationSender { void send(String to, String msg); }

@Service("emailSender")
@Primary                                   // default winner
class EmailSender implements NotificationSender { /* ... */ }

@Service("smsSender")
class SmsSender implements NotificationSender { /* ... */ }

@Service
class AlertService {
    private final NotificationSender defaultSender;
    private final NotificationSender smsSender;
    private final Map<String, NotificationSender> all;

    AlertService(NotificationSender defaultSender,              // gets EmailSender (primary)
                 @Qualifier("smsSender") NotificationSender smsSender,
                 Map<String, NotificationSender> all) {          // both, keyed by bean name
        this.defaultSender = defaultSender;
        this.smsSender = smsSender;
        this.all = all;
    }
}
```

Primary supplies the default, Qualifier picks explicitly, and the Map injection gives strategy-style lookup by name.

## Key points

- Resolution order: type, then @Primary, then @Qualifier, then name fallback.
- @Qualifier beats @Primary because it is more specific.
- Inject List or Map of the interface to get all implementations.
- @Autowired(required = false) or Optional makes a dependency optional.

## Common follow-up questions

- What is the difference between @Autowired and @Resource?
- How would you implement the strategy pattern using Spring beans?
- What does NoSuchBeanDefinitionException tell you?

## Interview tips

- Walk through the resolution order; it shows you understand the mechanism.
- Mention Map injection for the strategy pattern as a bonus.

## Concepts covered

Autowired, Qualifier, Primary, Ambiguous Beans

Previous: [@Component, @Service, @Repository and @Controller](https://www.internhack.in/learn/interview/spring-boot-interview/spring-stereotype-annotations) · Next: [How @SpringBootApplication and Auto-Configuration Work](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-autoconfiguration-springbootapplication) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Spring Boot Starters and Dependency Management](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-starters)
- [application.properties, YAML and Profiles](https://www.internhack.in/learn/interview/spring-boot-interview/spring-properties-yaml-profiles)
- [@RestController vs @Controller](https://www.internhack.in/learn/interview/spring-boot-interview/spring-restcontroller-vs-controller)
- [@PathVariable vs @RequestParam vs @RequestBody](https://www.internhack.in/learn/interview/spring-boot-interview/spring-request-mapping-pathvariable-requestparam-requestbody)
- [Bean Validation with @Valid and @Validated](https://www.internhack.in/learn/interview/spring-boot-interview/spring-validation-valid)
- [Global Exception Handling with @ControllerAdvice](https://www.internhack.in/learn/interview/spring-boot-interview/spring-controlleradvice-global-exception-handling)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
