Sub topic 8
How Spring picks what to inject: types, @Primary and @Qualifier
This chapter assumes you know Java interfaces and constructors, and that you have seen @Service, @Configuration and @Bean. It explains how Spring chooses a bean when several could fit a dependency.
Matching by type first
When Spring sees a constructor parameter, it looks for beans whose type is assignable to that parameter's type. A bean of a class that implements MessageSender is a candidate for a MessageSender parameter.
- One candidate: Spring injects it.
- No candidate: startup fails with
NoSuchBeanDefinitionException. - Several candidates: Spring needs a tie-breaker. If it finds none, startup fails with
NoUniqueBeanDefinitionException.
An ambiguous setup
Suppose the application has two senders. Both are MessageSender beans, so any injection point of that type is ambiguous unless you add guidance.
@Configuration
public class SenderConfig {
@Bean
@Primary
public MessageSender emailSender() {
return (to, body) -> System.out.println("email: " + body);
}
@Bean
public MessageSender smsSender() {
return (to, body) -> System.out.println("sms: " + body);
}
}By default, the bean name is the method name, so these beans are named emailSender and smsSender.
@Primary sets the default
@Primary marks one bean as the preferred choice when several match. NotificationService from earlier chapters takes a plain MessageSender. It now receives emailSender with no change to its code.
Use @Primary when one implementation is the normal choice and the others are exceptions.
@Qualifier selects a specific bean
@Qualifier names the bean you want at the injection point. It overrides @Primary.
@Service
public class AlertService {
private final MessageSender sender;
public AlertService(@Qualifier("smsSender") MessageSender sender) {
this.sender = sender;
}
}AlertService gets smsSender even though emailSender is primary.
Falling back to the parameter name
If no qualifier and no primary exist, Spring compares the parameter name with the bean names. A parameter called smsSender would match the bean smsSender. This only works when parameter names are kept in the compiled class. Spring Boot's build plugins and Gradle and Maven setups usually do that, but relying on it is fragile. A rename silently changes the wiring. Prefer an explicit @Qualifier.
Injecting every candidate
Sometimes you want all matching beans. Declare a collection and Spring injects every candidate, so ambiguity does not arise.
@Service
public class BroadcastService {
private final List<MessageSender> senders;
public BroadcastService(List<MessageSender> senders) {
this.senders = senders;
}
public void broadcast(String to, String body) {
senders.forEach(s -> s.send(to, body));
}
}A Map<String, MessageSender> also works. The keys are the bean names.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` | No bean of that type exists, often because the class is not scanned or has no annotation | Add the annotation, fix the scan base package, or add a `@Bean` method |
| `NoUniqueBeanDefinitionException` | Several beans match and nothing breaks the tie | Add `@Primary` to one, or add `@Qualifier` at the injection point |
| Wrong bean injected | A `@Qualifier` or `@Primary` is chosen differently than you assumed | Check which one wins: a qualifier beats a primary |
| Two `@Primary` beans of one type | More than one bean is marked primary | Keep only one, and use qualifiers for the rest |
Exercise
A project has beans emailSender (marked @Primary) and smsSender, both of type MessageSender. Which bean does each constructor receive? (a) ReportService(MessageSender sender) (b) AlertService(@Qualifier("smsSender") MessageSender sender) (c) AuditService(MessageSender other), with no annotations.
Show answer
(a) emailSender, because it is primary and no qualifier is present. (b) smsSender, because a qualifier overrides @Primary. (c) emailSender, because the primary bean is used before the parameter name is considered, and other matches no bean name anyway.