Repaso
Español
Spring, JPA & Java WebIntermediateSPR-13

What happens if two beans of the same type exist and you inject that type without more information?

Options

  1. Spring picks one of the beans at random for you
  2. Startup fails (NoUniqueBeanDefinition); use @Primary (Correct option)
  3. Spring injects both of the beans into the same field
  4. Nothing fails, and the field is injected as null

Answer

Startup fails with NoUniqueBeanDefinitionException; resolve it with @Primary or @Qualifier

Why

If PaymentGateway has two implementations (StripeGateway, PaypalGateway), Spring cannot know which one you want and fails at startup (good: you find out immediately).

Fixes: mark one as @Primary (default choice), use @Qualifier("stripeGateway") at the injection point, or inject List<PaymentGateway> / Map<String, PaymentGateway> if you want all of them.

Remember

Ambiguity => @Primary or @Qualifier.

Key terms

Practice this question in Repaso