Path 5 · lesson 2 of 5
Two beans of one type: which one is injected
Spring narrows the candidates by qualifier, then by @Primary, then by name, and refuses to start when more than one is left. The order decides which bean you silently get.
What you will learn
- State the order in which Spring narrows several candidates down to one
- Read a
NoUniqueBeanDefinitionExceptionand name the two ways it can arise - Predict the injected bean when a qualifier,
@Primaryand a matching name disagree - Inject every bean of a type on purpose, as a list or as a map by bean name
- Explain how adding a dependency can change which bean an existing class receives
Before you start
The concept
Spring injects by type. A constructor that asks for a PaymentGateway gets the bean of that type. With one bean there is nothing to decide. With two, Spring has to choose, and it follows a fixed order to do so.
- Qualifier. If the injection point carries
@Qualifier("x"), only beans with that qualifier or that bean name remain. - Primary. If exactly one remaining candidate is marked
@Primary, it wins. - Name. Otherwise, if the name of the parameter or field equals the name of one candidate, that one wins.
- Refuse. If more than one candidate is still left, the application does not start.
Why it exists
Two beans of one type is normal in a real service: a primary and a reporting DataSource, two payment providers, an ObjectMapper for the API and another for a partner's format, a RestClient per downstream system. Each pair is a place where a write can go to the wrong database or a payment to the wrong provider.
It also arrives from outside. A library you add may register its own bean of a type you already have. Depending on the annotations involved, the application then either fails at startup or keeps starting with a different bean injected.
How it works inside
The lab registers two PaymentGateway beans, stripeGateway and adyenGateway, and builds a Checkout that needs one. Each numbered line is a separate small application context with a different injection point.
Program outputjava -jar target/spring-production-lab-1.0.jar --demo=beans (Spring Boot 3.5.16, Java 21)
Real JVM output1. parameter named 'gateway', no hint -> FAILS AT STARTUP
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'lab.PaymentGateway' available: expected single matching bean but found 2: stripeGateway,adyenGateway
2. parameter named 'adyenGateway' -> adyen
3. @Qualifier("stripeGateway") -> stripe
4. @Qualifier("stripeGateway") adyenGateway -> stripe
5. adyen is @Primary, parameter 'gateway' -> adyen
6. adyen is @Primary, parameter 'stripeGateway' -> adyen
...
7. both are @Primary -> FAILS AT STARTUP
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'lab.PaymentGateway' available: more than one 'primary' bean found among candidates: [stripeGateway, adyenGateway]
8. List<PaymentGateway> and Map<String, ...> -> Router[all=[Gateway[name=stripe], Gateway[name=adyen]], byName={stripeGateway=Gateway[name=stripe], adyenGateway=Gateway[name=adyen]}]@Primary beating a parameter name: the parameter is called stripeGateway and receives adyen. Case 7 fails with a different message, because two primaries are as ambiguous as none.| Injection point | Result | Why |
|---|---|---|
PaymentGateway gateway | Startup fails | Two candidates, no qualifier, no primary, no name match |
PaymentGateway adyenGateway | adyen | Name fallback: the parameter name equals a bean name |
@Qualifier("stripeGateway") PaymentGateway adyenGateway | stripe | The qualifier is applied before the name is looked at |
PaymentGateway stripeGateway, adyen is @Primary | adyen | Primary is applied before the name is looked at |
List<PaymentGateway> | Both | A collection asks for all candidates, so there is nothing to choose |
The name fallback depends on the compiler keeping parameter names in the class file, which needs the -parameters flag. Spring Boot's Maven and Gradle plugins set it. A project built another way loses the names, and with them case 2.
Spring Boot's own auto-configured beans mostly carry @ConditionalOnMissingBean: they step back when you define a bean of that type yourself. That is why declaring your own ObjectMapper replaces Boot's and does not produce two. A second DataSource is the classic exception: once you define one, Boot's is gone and you must define and mark both.
Architecture
Drawing diagram…
A flowchart. Starting from all beans of the type, a qualifier on the injection point keeps only matching beans. Then, if exactly one candidate is primary it is injected. Otherwise, if the parameter name equals a bean name that bean is injected. Otherwise startup fails with NoUniqueBeanDefinitionException.
flowchart TD
A["Injection point needs a PaymentGateway"] --> B["All beans of that type"]
B --> C{"@Qualifier on the injection point?"}
C -->|"yes"| D["Keep only matching beans"]
C -->|"no"| E{"Exactly one @Primary?"}
D --> E
E -->|"yes"| W["Inject it"]
E -->|"no"| F{"Parameter name equals a bean name?"}
F -->|"yes"| W
F -->|"no"| X["NoUniqueBeanDefinitionException: the application does not start"]- A qualifier is the only rule stated at the injection point, next to the code that uses the bean.
@Primaryand bean names are stated somewhere else and affect every injection point at once. - The diagram covers a single bean. Asking for a
List, aMap<String, T>or anObjectProvider<T>skips the whole decision.
Step by step
Drawing diagram…
A sequence diagram. At application start the bean factory creates CheckoutService, finds two PaymentGateway beans, sees no qualifier and that adyenGateway is primary, and passes adyenGateway to the constructor, although the constructor parameter is named stripeGateway.
sequenceDiagram
participant App as Application start
participant BF as Bean factory
participant CS as CheckoutService
App->>BF: create CheckoutService
BF->>BF: find beans of type PaymentGateway
Note over BF: stripeGateway and adyenGateway
BF->>BF: no qualifier, adyenGateway is primary
BF->>CS: new CheckoutService(adyenGateway)
Note over CS: the parameter is named stripeGateway, and holds adyen- Resolution happens when the bean is created. After that the reference is fixed, so a wrong choice affects every request for the life of the process.
- Nothing is logged for a successful resolution. The only way to see the choice is to look at the injected object.
In a real system
A team adds a read replica. They define a second DataSource bean and mark the original @Primary so that existing code keeps working. Months later someone writes a report job and names its constructor parameter replicaDataSource. It compiles, it starts, and it runs its heavy queries on the primary, because primary is applied before the name.
- Qualify the unusual one at every use.
@Primaryfor the default and an explicit@Qualifierwherever the other is wanted. - Prefer a type of your own. A small wrapper such as
ReportingDatabasecannot be confused with anything, and needs no annotation. - Use
@Fallbackfor defaults a user may replace. Since Spring Framework 6.2 a bean marked@Fallbackis used only when no other candidate exists, the reverse of@Primary.
Java and Spring Boot
Two gateways and three ways to use them, as in labs/jvm/spring-production/src/main/java/lab/BeansDemo.java: one chosen by qualifier, one default, and all of them by name.
@Configurationclass PaymentConfig { @Bean @Primary PaymentGateway stripeGateway() { return new Gateway("stripe"); } @Bean PaymentGateway adyenGateway() { return new Gateway("adyen"); }}@Serviceclass CheckoutService { // gets the primary: stripe CheckoutService(PaymentGateway gateway) { }}@Serviceclass RefundService { // asks for adyen by name, on purpose RefundService(@Qualifier("adyenGateway") PaymentGateway gateway) { }}@Serviceclass GatewayRouter { // all of them, keyed by bean name GatewayRouter(Map<String, PaymentGateway> gateways) { }}Why it is written this way
@Primarymarks the default once. Everything that does not care keeps working when a second gateway is added.@Qualifierat the injection point is visible in the class that depends on the choice, so a reader does not have to search the configuration.- A
Map<String, PaymentGateway>receives every bean of the type with its bean name as the key. It is the natural shape for choosing a provider per request.
Wrong, then right
A report job that must read from the replica. The incorrect version relies on the parameter name. The corrected version says which bean it wants.
Incorrect implementation
@Configurationclass DataConfig { @Bean @Primary DataSource primaryDataSource() { return build("primary"); } @Bean DataSource replicaDataSource() { return build("replica"); }}@Componentclass MonthlyReportJob { private final DataSource dataSource; MonthlyReportJob(DataSource replicaDataSource) { // name only this.dataSource = replicaDataSource; }}Why it is written this way
- The parameter name suggests the replica. The rule that reads names is never reached, because a primary exists.
Why it fails
- With one candidate marked
@Primary, resolution stops at the primary step. The parameter name is a fallback for when there is no primary, so it is not consulted. - The job starts and works. It simply runs its long queries against the primary database, which is the one thing the replica was added to prevent.
Corrected implementation
@Componentclass MonthlyReportJob { private final DataSource dataSource; MonthlyReportJob(@Qualifier("replicaDataSource") DataSource dataSource) { this.dataSource = dataSource; }}Why it is written this way
- The qualifier is applied first and removes the primary from the candidates. If the bean is ever renamed, startup fails instead of quietly switching database.
Trade-offs
- The qualifier is a string. A typo is found at startup, not at compile time. A custom qualifier annotation or a wrapper type moves the check to the compiler.
- Every class that wants the replica must say so. That is extra text, and it is also the point: the unusual choice is stated where it is made.
Hands-on exercise
Predict eight injections
Read the eight injection points in the lab source, write down what each receives, then compare with the real output.
Steps · 0 of 4 done
What you should see
Cases 1 and 7 fail at startup with two different messages. The ninth case injects stripe: the qualifier is applied before @Primary, so a qualifier is the one way to ask for the non-primary bean.
What can go wrong
Trusting the parameter name
- Symptom
- A field called
replicaDataSourcetalks to the primary database. - Cause
- A
@Primarycandidate exists, so the name fallback is never reached. - Fix
- Add
@Qualifierat the injection point whenever you want anything other than the default.
A second @Primary from a library
- Symptom
- After a dependency upgrade the application fails with "more than one 'primary' bean found among candidates".
- Cause
- The library now marks its own bean of the same type as primary.
- Fix
- Qualify your injection points, or exclude the library's auto-configuration if you do not use its bean.
Defining a second DataSource and losing the first
- Symptom
- Adding a reporting
DataSourcemakes the application start with only that one, and the main repositories fail. - Cause
- Spring Boot's auto-configured
DataSourcebacks off as soon as anyDataSourcebean is defined. - Fix
- Define both explicitly, mark the main one
@Primary, and qualify the other.
How to troubleshoot
Startup fails: "expected single matching bean but found 2"
Check
The bean names listed at the end of the message
- How to read it
- Those are the candidates. Decide which is the default and mark it
@Primary, or qualify this injection point.
The application starts but a class seems to use the wrong bean
Check
GET /actuator/beans, or log the injected object in the constructor
- How to read it
- The beans endpoint lists every bean with its type and its dependencies by name, so you can see which candidate was wired in.
A bean you expected from Spring Boot is missing
Check
Start with --debug and read the conditions evaluation report
- How to read it
- The report says which auto-configuration did not match and why, typically "found beans of type" for a bean you defined yourself.
Key takeaways
- With several candidates Spring applies the qualifier, then
@Primary, then the parameter or field name, and fails at startup if more than one is left. @Primarybeats a matching name. A parameter named after a bean is not a request for that bean.- A qualifier at the injection point is the only choice written next to the code that depends on it.
- Ask for a
Listor aMap<String, T>when you want every bean of a type.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 2
A service has two RestClient beans, billingClient and ledgerClient. billingClient is @Primary. A new class has the constructor Reconciler(RestClient ledgerClient) and no other annotation.
What does the Reconciler receive?
Scenario 2 of 2
An application with one Clock bean of its own adds a library. On the next start it fails with NoUniqueBeanDefinitionException: expected single matching bean but found 2: clock,auditClock. Twelve classes inject Clock.
Which change fixes it with the least risk of a silent mistake?
References
References: Spring Framework reference: Fine-tuning annotation-based autowiring with @Primary or @Fallback ↗ · Spring Framework reference: Fine-tuning annotation-based autowiring with qualifiers (qualifier, then name fallback) ↗ · Spring Framework reference: Using @Autowired (arrays, collections and maps of all beans of a type) ↗ · Report a problem