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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
