The 30 second answer
Two beans of the same type don't automatically cause a failure. For a single dependency, Spring tries to choose one using rules such as @Primary, a matching injection-point name, @Priority and a unique default candidate. If ambiguity remains when that dependency is resolved, it throws NoUniqueBeanDefinitionException, usually failing startup for an eager singleton. Injecting a list or a bean-name-keyed map instead collects the matching beans, so having multiple candidates is expected rather than ambiguous.
The tie-break logic is in one method:
// Step 1: check primary candidate
String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
if (primaryCandidate != null) {
return primaryCandidate;
}
// Step 2a: match bean name against declared dependency name
String dependencyName = descriptor.getDependencyName();
if (dependencyName != null) {
for (String beanName : candidates.keySet()) {
if (matchesBeanName(beanName, dependencyName)) {
return beanName;
}
}
}
// Step 2b: match bean name against qualifier-suggested name
// Step 3: check highest priority candidate
// Step 4: pick unique default-candidate
// Step 5: pick directly registered dependencyDefaultListableBeanFactory.determineAutowireCandidate L2038-L2082 (shortened)
If the method returns null, the factory throws NoUniqueBeanDefinitionException (L2105).
Example:
@Bean PaymentGateway stripeGateway() { ... }
@Bean PaymentGateway paypalGateway() { ... }
@Service
class CheckoutService {
CheckoutService(PaymentGateway gateway) { } // fails: no tie-break
// CheckoutService(PaymentGateway stripeGateway) // works: name match
}Ways to fix it:
- **
@Primary** on the bean that should be the default. - **
@Qualifier("stripeGateway")** at the injection point. This is the clearest option. - Name match: name the parameter like the bean. This works but is fragile: renaming a variable changes wiring. Constructor parameter names are only known if the code is compiled with
-parameters; Spring Framework 6.1 removed the older bytecode-based fallback. - Inject all:
List<PaymentGateway>(ordered by@Order) orMap<String, PaymentGateway>keyed by bean name, then choose at runtime. Good for strategy patterns. - **
@Fallback** (Spring Framework 6.2+): marks a bean that is used only when no other candidate exists.
Interview trap: the error is NoUniqueBeanDefinitionException, not NoSuchBeanDefinitionException. Also, ObjectProvider<T>.getIfUnique() returns null instead of failing when there are several beans.
Editor's note: prefer @Qualifier or @Primary in shared code; relying on parameter names hides intent.