Sub topic 8
How Spring picks what to inject: types, @Primary and @Qualifier
This chapter assumes you know constructor injection, the difference between a bean definition and a bean instance, and how @Component scanning and @Bean methods register beans. It covers what Spring does when a dependency could be satisfied by zero, one or several beans.
Resolution starts with the type
When Spring sees a dependency, it asks the container for beans whose type is assignable to the declared type. The dependency can be a constructor parameter, a setter parameter or a field. Interface, superclass and generic arguments all count. The parameter name is not the first thing checked.
With exactly one candidate, Spring injects it. With zero or several, it moves on to further rules or fails.
public interface MessageSender {
void send(String to, String body);
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SenderConfig {
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email to " + to + ": " + body);
}
}If emailSender is the only MessageSender bean, any class that asks for a MessageSender receives it, whatever the parameter is called.
The decision sequence
When more than one bean matches, Spring narrows the candidates in a fixed order.
In practice, a qualifier filters the candidates first, so an explicit @Qualifier always beats @Primary. Primary, priority and the name fallback only settle what is left after filtering.
Zero candidates
If no bean matches, container startup fails. The error is an UnsatisfiedDependencyException that wraps a NoSuchBeanDefinitionException. The message names the type and the injection point, for example "No qualifying bean of type 'MessageSender' available".
Typical causes:
- The class is not annotated, or it sits outside the packages that component scanning covers.
- The
@Configurationclass that defines the bean is not registered. - A profile or condition excluded the bean.
- A typo in the type, or a different generic argument than expected.
When a dependency really is optional, say so at the injection point. Do not leave it to chance.
import java.util.Optional;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
@Service
public class AuditService {
private final Optional<MessageSender> sender;
public AuditService(Optional<MessageSender> sender) {
this.sender = sender;
}
}
@Service
class ReportService {
private final ObjectProvider<MessageSender> senders;
ReportService(ObjectProvider<MessageSender> senders) {
this.senders = senders;
}
void run() {
MessageSender s = senders.getIfAvailable();
if (s != null) {
s.send("ops", "report ready");
}
}
}Optional<T> and @Nullable both work for optional dependencies. ObjectProvider<T> also lets you defer the lookup until you need it. It additionally supports getIfUnique(), which returns null instead of throwing when several beans match. @Autowired(required = false) is the older form of the same idea.
Several candidates: @Primary
@Primary marks one bean as the default choice when several of a type exist. Use it on the bean that most consumers want, and override it only where needed.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class MultiSenderConfig {
@Bean
@Primary
public MessageSender emailSender() {
return (to, body) -> System.out.println("email to " + to + ": " + body);
}
@Bean
public MessageSender smsSender() {
return (to, body) -> System.out.println("sms to " + to + ": " + body);
}
}@Primary can also sit on a class that is annotated with @Component or a stereotype. Only one candidate of a given type may be primary. If two beans are both primary, Spring throws NoUniqueBeanDefinitionException.
Choosing explicitly: @Qualifier
@Qualifier("name") at the injection point restricts the candidates to beans that carry that qualifier. By default, a bean's qualifier is its bean name. For a @Bean method that is the method name. For a scanned class it is the decapitalized class name, such as smsSender for SmsSender.
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class AlertService {
private final MessageSender sender;
public AlertService(@Qualifier("smsSender") MessageSender sender) {
this.sender = sender;
}
public void alert(String user) {
sender.send(user, "Security alert");
}
}Here AlertService gets smsSender even though emailSender is primary.
On a scanned class you can assign a qualifier that is not the bean name:
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("urgent")
public class PagerSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("page to " + to + ": " + body);
}
}Injecting with @Qualifier("urgent") now finds PagerSender regardless of what its bean name is. Prefer this over bean names when the label expresses a role, because renaming a class or method then cannot silently break the wiring.
Qualifier strings and meta-annotations
A plain string has no compile-time check. A typo shows up as NoSuchBeanDefinitionException at startup. To get compiler support, define your own annotation and meta-annotate it with @Qualifier:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface Sms {
}Put @Sms on the bean and on the injection point. Both places must carry it, or the filter will not match.
The name fallback
If several candidates remain and nothing is primary or prioritized, Spring compares the injection point's name with bean names. A parameter named smsSender selects the bean smsSender.
public AlertService(MessageSender smsSender) {
this.sender = smsSender;
}This works only if parameter names are available at runtime. Spring Boot's Maven and Gradle plugins compile with -parameters. A plain javac build does not unless you pass that flag. Because a rename can change which bean is injected, treat this fallback as a convenience, not a design tool. An explicit @Qualifier is easier to read and to review.
Injecting every candidate
Sometimes you want all matching beans, not one. Declare a collection, and Spring injects every bean of the element type:
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
@Service
public class BroadcastService {
private final List<MessageSender> senders;
private final Map<String, MessageSender> byName;
public BroadcastService(List<MessageSender> senders,
Map<String, MessageSender> byName) {
this.senders = senders;
this.byName = byName;
}
public void broadcast(String user, String body) {
senders.forEach(s -> s.send(user, body));
}
public MessageSender named(String beanName) {
return byName.get(beanName);
}
}In a Map<String, T>, the keys are bean names. Order in a List follows @Order, Ordered or @Priority where present. Otherwise it follows registration order, which you should not rely on. @Primary and the name fallback do not apply to collections, since every match is wanted. An explicit @Qualifier still filters the collection.
Running it
A small program shows the three outcomes together:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(
MultiSenderConfig.class, AlertService.class)) {
ctx.getBean(AlertService.class).alert("ana");
System.out.println(ctx.getBeansOfType(MessageSender.class).keySet());
}
}
}The output includes sms to ana: Security alert, and the bean names emailSender and smsSender, in registration order. Registering AlertService directly as a component class is enough here, because the context creates a bean from it.
Reading the errors
| Symptom | Exception | Likely cause |
|---|---|---|
| "No qualifying bean of type" | `NoSuchBeanDefinitionException` (wrapped in `UnsatisfiedDependencyException`) | Missing registration, scan path, profile, or a qualifier typo |
| "expected single matching bean but found 2" | `NoUniqueBeanDefinitionException` | Several beans, no primary, no qualifier, no name match |
| Wrong bean injected, no error | None | `@Primary` or the name fallback chose something you did not expect |
The third row is the dangerous one, because nothing fails. When a service must use a specific implementation, qualify it.
Choosing between the tools
- Use
@Primaryfor a sensible default that most consumers want. - Use
@Qualifierwhen a consumer needs one specific implementation. - Use a collection when the consumer must work with all implementations.
- Use
OptionalorObjectProviderwhen the dependency may be absent. - Avoid the name fallback in code you expect others to maintain.
Exercise
A context has two MessageSender beans, emailSender (marked @Primary) and smsSender. A class has the constructor NoticeService(@Qualifier("smsSender") MessageSender sender). Which bean is injected, and what happens if you remove the @Qualifier and rename the parameter to pushSender?
Show answer
With the qualifier, smsSender is injected, because the qualifier filters the candidates before @Primary is considered. Without it, and with the parameter renamed to pushSender, emailSender is injected because it is the primary bean. The name fallback only applies when no bean is primary, and it would not match anyway since no bean is named pushSender.
Exercise
BroadcastService declares List<MessageSender> in its constructor, and two MessageSender beans exist, one of them @Primary. How many senders does the list contain, and why does startup not fail with NoUniqueBeanDefinitionException?
Show answer
The list contains both senders. For a collection injection point, Spring wants every matching bean, so there is no ambiguity to resolve and @Primary is not used to pick one.