Fix NoUniqueBeanDefinitionException With Qualifier
Resolve the Spring error about several matching beans with @Primary, @Qualifier or by injecting all of them, and learn which one fits.

Spring injects a bean by type. When two beans match the same type, it has no way to pick one on its own, so it stops with an exception at startup. The message is precise, and it names the candidates:
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'dev.javahacks.PaymentGateway' available:
expected single matching bean but found 2: stripeGateway,paypalGatewayRead it before you change anything. It tells you the type that was requested, how many beans matched and their names. The fix is a decision about intent: do you want one of them as the default, a specific one at this injection point, or all of them? Four mechanisms express those answers, and picking the right one matters because the wrong one hides a design problem. This post covers Spring Framework 7 and Spring Boot 4. The opposite failure, no match at all, is covered in no qualifying bean.
Choice 1: one default with @Primary
@Component
@Primary
class StripeGateway implements PaymentGateway { }
@Component
class PaypalGateway implements PaymentGateway { }@Primary marks the bean that wins when nothing more specific is asked for. Every plain @Inject PaymentGateway now gets Stripe, and the exception disappears. It is the right tool when one implementation is the normal choice and the others are exceptions. It is the wrong tool when there is no normal choice, because it makes an arbitrary pick look like a design. Only one bean of a type can be primary, and two primaries produce the same exception again.
Choice 2: name the one you want
@Service
class CheckoutService {
private final PaymentGateway gateway;
CheckoutService(@Qualifier("paypalGateway") PaymentGateway gateway) {
this.gateway = gateway;
}
}@Qualifier selects by bean name, which defaults to the class name with a lower-case first letter. It overrides @Primary at that injection point. A string name has a weakness: rename the class and the qualifier silently stops matching, and the failure moves from the compiler to startup. A custom qualifier annotation avoids it:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@interface Paypal { }
@Component @Paypal
class PaypalGateway implements PaymentGateway { }
CheckoutService(@Paypal PaymentGateway gateway) { ... }Now the choice is a type the compiler checks, and a search for usages of @Paypal finds every place that depends on it.
Choice 3: take all of them
When the code genuinely wants every implementation, inject a collection and Spring supplies all the matching beans:
@Service
class PaymentRouter {
private final Map<String, PaymentGateway> gateways;
PaymentRouter(Map<String, PaymentGateway> gateways) {
this.gateways = gateways; // keys are bean names
}
PaymentGateway forProvider(String provider) {
PaymentGateway gateway = gateways.get(provider + "Gateway");
if (gateway == null) throw new IllegalArgumentException("unknown provider " + provider);
return gateway;
}
}A List<PaymentGateway> works the same way and keeps the order defined by @Order. This is the strategy pattern with Spring doing the registration, as discussed in the strategy pattern, and it is the correct answer to the case of several implementations chosen at run time. Spring also offers ObjectProvider<PaymentGateway>, which defers the lookup and lets you call getIfUnique() or stream the candidates.
Choice 4: match by parameter name
If no qualifier is present and the parameter name equals a bean name, Spring uses that bean as a last resort:
CheckoutService(PaymentGateway paypalGateway) { ... }This works only when the class is compiled with the -parameters option, because the name must be available at run time. Spring Framework 6.1 stopped reading parameter names from debug information, so a build without -parameters loses it. Spring Boot's Maven and Gradle plugins set the flag, which is why it often works by accident. It is fragile: renaming a parameter in a refactoring changes behaviour. Treat it as a fallback to recognise, not a mechanism to design with.
Find the accidental duplicate
Often the exception is not about a design choice at all. A second bean exists that nobody intended: a configuration class imported twice, a scanned package that includes a test configuration, or an auto-configuration that provides a default beside the bean you defined yourself. Find out where the candidates come from. Start the application with --debug to print the conditions report, or query the beans endpoint if Actuator is on:
curl -s localhost:8080/actuator/beans | jq '.contexts[].beans | to_entries[] | select(.key|test("Gateway")) | {name: .key, type: .value.type}'The output shows each bean's type and the resource that defined it, and the second definition is usually obvious. If a library supplies a default that your bean should replace, the library should have marked it @ConditionalOnMissingBean; if it did not, exclude its auto-configuration. Deleting the stray definition is better than adding @Primary to paper over it, because the duplicate usually carries other consequences, such as two connection pools or two schedulers.
Choosing between them
| You want | Use |
|---|---|
| One implementation is the normal default | @Primary on it |
| A specific one at one injection point | @Qualifier, preferably a custom annotation |
| Every implementation, to choose at run time | List, Map or ObjectProvider |
| Only one to exist per environment | @Profile or a conditional annotation on the beans |
| A single bean and the second is a mistake | Remove the duplicate |
The profile option deserves a mention: if the Stripe gateway is for production and a fake is for tests, mark each with @Profile and only one exists at a time, so the ambiguity never arises. It also makes the dev environment honest about which one is active.
What to do in a library or a starter
If you write a starter that provides a default bean, make it replaceable instead of forcing users to fight it. Mark the default with @ConditionalOnMissingBean, so that it backs off when the application defines its own of the type. Two competing definitions then never reach the container together, and the application author never meets this exception because of your code. In an application, prefer overriding by defining your own bean of the same type over adding a second and sorting it out with @Primary.
Testing the choice
Add a small test that proves the wiring you intended. A Spring Boot test with the real context, injecting the consumer, checks that the right implementation is behind it:
@SpringBootTest
class PaymentWiringTest {
@Autowired CheckoutService checkout;
@Autowired ApplicationContext context;
@Test
void checkoutUsesPaypal() {
assertThat(checkout.gateway()).isInstanceOf(PaypalGateway.class);
}
@Test
void exactlyTwoGatewaysExist() {
assertThat(context.getBeansOfType(PaymentGateway.class)).hasSize(2);
}
}The second test is a guard against the accidental duplicate. If a refactoring adds a third bean, the test fails with a message that names the count, long before an injection point becomes ambiguous in a way that is harder to read. Tests that replace a bean with a fake should declare the fake with the framework's own mechanism, such as @MockitoBean, which replaces the bean by type and does not add a second candidate.
Where this does not apply
The same exception can be raised for a type you did not think of, such as ObjectMapper or DataSource, when a library and your configuration both define one. The cause is the same and so is the investigation. How the container resolves candidates is explained in how the Spring container works, and a closely related error appears when a bean name is missing entirely, described in [NoSuchBeanDefinitionException](/library/nosuchbeandefinitionexception-fix-spring). The authoritative text is the Spring reference on fine-tuning annotation-based autowiring with qualifiers, and the Javadoc is under docs.spring.io.


