Video in progress

Junior 🌱 Spring

If one interface has two implementations, which one does Spring inject?

It can't choose by itself and throws NoUniqueBeanDefinitionException. You tell it which one to use with @Primary or @Qualifier, or take all of them as a List/Map.

📖 Answer

Say there are two payment providers:

public interface PaymentGateway { void pay(long amount); }

@Component("click") class ClickGateway implements PaymentGateway { ... }
@Component("payme") class PaymeGateway implements PaymentGateway { ... }

If you ask for PaymentGateway gateway, Spring finds two candidates and fails at startup.

Here's how you fix it:

@Primary // this one becomes the default
@Component("click") class ClickGateway ...

public CheckoutService(@Qualifier("payme") PaymentGateway gateway) { ... }

Sometimes you need all of them — for example, depending on which provider the user picked:

public CheckoutService(Map<String, PaymentGateway> gateways) {
    this.gateways = gateways; // key is the bean name: "click", "payme"
}

In practice this is much cleaner than an if/else chain: when a new provider comes along, you write one new class and that's it.