What happens if two beans of the same type exist and you inject that type without more information?
Options
- Spring picks one of the beans at random for you
- Startup fails (NoUniqueBeanDefinition); use
@Primary(Correct option) - Spring injects both of the beans into the same field
- 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.