Video in progress

In Spring, how do you inject several strategies through a `Map` and pick one without if-else?

Spring can inject all implementations of one interface as a List<T> or a Map<String, T>; the Map key is the bean name. An even cleaner way is for each strategy to have a method that returns its own type, and to build a map keyed by an enum in the constructor.

📖 Answer

The fastest option:

@Component("CLICK") class ClickPayment implements PaymentProvider { ... }
@Component("PAYME") class PaymePayment implements PaymentProvider { ... }

@Service
class PaymentRouter {
    private final Map<String, PaymentProvider> providers;
    PaymentRouter(Map<String, PaymentProvider> providers) { this.providers = providers; }

    PaymentProvider get(String code) {
        var p = providers.get(code);
        if (p == null) throw new IllegalArgumentException("Noma'lum provayder: " + code);
        return p;
    }
}

The downside is that the key depends on the bean name: if someone changes the name in @Component, you get null on prod.

This is what I usually do:

interface PaymentProvider {
    ProviderType type();
    PaymentResult charge(Charge c);
}

@Service
class PaymentRouter {
    private final Map<ProviderType, PaymentProvider> byType;

    PaymentRouter(List<PaymentProvider> all) {
        this.byType = all.stream()
            .collect(Collectors.toUnmodifiableMap(PaymentProvider::type, p -> p));
    }
}

If two providers return the same type(), toUnmodifiableMap throws an IllegalStateException while the application is starting, so the error shows up at startup, not in prod. To add a provider you just write a new @Component, and the router doesn't change.