Member-only story
Delete the switch: Spring Injects the Strategy Pattern for You
If you have written any Spring service, you have written this switch at least once. Something arrives with a type on it — a payment method, a notification channel, a file format — and a service method branches on that type to decide what to do. It starts as two cases and it is fine. Then a third payment provider ships, then a fourth, and now every new type means editing the same method, the same switch, and the same test. This post is about deleting that switch entirely, using a Spring feature you may not know is there: injecting a Map<String, T> of beans.
The switch that keeps growing
Here is the shape of it. A payment service that picks a processor by method name.
@Service
@RequiredArgsConstructor
@Slf4j
public class PaymentService {
private final StripeProcessor stripeProcessor;
private final PaypalProcessor paypalProcessor;
private final BankTransferProcessor bankTransferProcessor;
public PaymentResult charge(PaymentRequest request) {
return switch (request.method()) {
case "STRIPE" -> stripeProcessor.process(request);
case "PAYPAL" -> paypalProcessor.process(request);
case "BANK_TRANSFER" -> bankTransferProcessor.process(request);
default -> throw new…








