Skip to content

Path 5 · lesson 2 of 5

Foundation15 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5.16 · Spring Framework 6.2

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 NoUniqueBeanDefinitionException and name the two ways it can arise
  • Predict the injected bean when a qualifier, @Primary and 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.

  1. Qualifier. If the injection point carries @Qualifier("x"), only beans with that qualifier or that bean name remain.
  2. Primary. If exactly one remaining candidate is marked @Primary, it wins.
  3. Name. Otherwise, if the name of the parameter or field equals the name of one candidate, that one wins.
  4. 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 output
1. 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]}]
Case 1 has no hint and fails, and the message names both candidates. Case 2 is rescued only by the parameter name. Case 4 shows a qualifier beating a parameter name that says the opposite. Case 6 shows @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 pointResultWhy
PaymentGateway gatewayStartup failsTwo candidates, no qualifier, no primary, no name match
PaymentGateway adyenGatewayadyenName fallback: the parameter name equals a bean name
@Qualifier("stripeGateway") PaymentGateway adyenGatewaystripeThe qualifier is applied before the name is looked at
PaymentGateway stripeGateway, adyen is @PrimaryadyenPrimary is applied before the name is looked at
List<PaymentGateway>BothA 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"]
How several candidates are narrowed to one, in the order Spring applies the rules.
  • A qualifier is the only rule stated at the injection point, next to the code that uses the bean. @Primary and bean names are stated somewhere else and affect every injection point at once.
  • The diagram covers a single bean. Asking for a List, a Map<String, T> or an ObjectProvider<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
Case 6 of the lab: the choice is made once, at startup, and nothing reports it.
  1. 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.
  2. 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. @Primary for the default and an explicit @Qualifier wherever the other is wanted.
  • Prefer a type of your own. A small wrapper such as ReportingDatabase cannot be confused with anything, and needs no annotation.
  • Use @Fallback for defaults a user may replace. Since Spring Framework 6.2 a bean marked @Fallback is 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.

src/main/java/com/example/checkout/PaymentConfig.javaJava
@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

  • @Primary marks the default once. Everything that does not care keeps working when a second gateway is added.
  • @Qualifier at 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

MonthlyReportJob.java (incorrect)Java
@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

MonthlyReportJob.java (corrected)Java
@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 can go wrong

Trusting the parameter name
Symptom
A field called replicaDataSource talks to the primary database.
Cause
A @Primary candidate exists, so the name fallback is never reached.
Fix
Add @Qualifier at 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 DataSource makes the application start with only that one, and the main repositories fail.
Cause
Spring Boot's auto-configured DataSource backs off as soon as any DataSource bean 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.
  • @Primary beats 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 List or a Map<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