Spring / Spring7 Intermediate to Advanced Interview questions
What happens when two beans of the same type exist without a @Primary or @Qualifier?
Spring fails fast at context startup with a NoUniqueBeanDefinitionException, listing the names of every candidate bean it found matching the requested type, rather than guessing which one the application meant.
NoUniqueBeanDefinitionException: expected single matching bean but found 2: stripeGateway, paypalGateway
There are three common ways to resolve it. Add @Primary to whichever bean should be the sensible default across the application, so unqualified injection points resolve to it automatically while other injection points can still explicitly request the alternative via @Qualifier. Add @Qualifier("beanName") directly at the specific injection point when there's no sensible "default" and each usage genuinely needs to pick deliberately. Or, as a fallback Spring itself uses, name the injected field or constructor parameter to exactly match one bean's name - after by-type matching is ambiguous, Spring tries by-name matching - though this is fragile since it depends on parameter names being preserved and is generally considered a less explicit, less recommended approach than the first two.
More Related questions...