Video in progress

Middle 🌱 Spring

How do you build the strategy pattern by injecting all implementations of an interface as a List or Map?

If you ask for List<PaymentProvider>, Spring injects all beans of that type; if you ask for Map<String, PaymentProvider>, it injects a map keyed by bean name. That way a new implementation is added without an if/switch chain.

📖 Answer

Say a different provider is used depending on the payment type:

public interface PaymentProvider {
    String code();                 // "CLICK", "PAYME", "UZCARD"
    PaymentResult pay(PaymentRequest r);
}

@Service
class PaymentRouter {
    private final Map<String, PaymentProvider> byCode;

    PaymentRouter(List<PaymentProvider> providers) {
        this.byCode = providers.stream()
                .collect(Collectors.toUnmodifiableMap(PaymentProvider::code, p -> p));
    }

    PaymentResult pay(String code, PaymentRequest r) {
        PaymentProvider p = byCode.get(code);
        if (p == null) throw new UnsupportedPaymentException(code);
        return p.pay(r);
    }
}

Adding a new provider means just writing a new @Component class. The router isn't touched.

A few details:

  • If you inject Map<String, X>, the key is the bean name (clickProvider). To tie it to business code, it's better to build the map yourself as above: a bean name can change in a refactoring.
  • toUnmodifiableMap fails at startup if two providers return the same code. That's good: the error doesn't reach production.
  • The List order is controlled with @Order or Ordered.
  • If there's no implementation at all, injecting a List fails; if it's optional, use ObjectProvider<X>.