Pluggable Payment Dispatch with Spring Bean Maps
Data Structure DesignModel answerLast updated
Design an extensible payment dispatcher in Spring where a Map of strategy beans is injected automatically and new payment methods need no changes to the service.
Build an Extensible Payment Dispatcher
An online store has to accept several payment methods, such as credit card, crypto, and possibly PayPal later. Design a small Spring-based component that routes a payment to the right handler without a growing chain of conditionals.
What to build
- A
PaymentStrategyinterface with a single operation,processPayment(double amount). - Two implementations of it:
CreditCardPaymentandCryptoPayment. - A
PaymentServicethat keeps its strategies in aMapkeyed by payment type. The map must be filled by Spring's dependency injection from allPaymentStrategybeans in the context, not by hand. - A method
executePayment(String type, double amount)onPaymentService. It finds the strategy registered fortypeand calls it withamount. If no strategy exists fortype, it throwsIllegalArgumentException.
Example
// Beans are managed by Spring
PaymentService service = ...;
// Finds the bean registered as "creditCard" and calls processPayment(100.0)
service.executePayment("creditCard", 100.0);
Discussion points
Be ready to explain:
- How the design lets you add a new payment method without editing
PaymentService(Open/Closed Principle). - Why a
Maplookup is preferable to a longif-elseorswitch. - What role bean naming, autowiring, and
@Qualifierplay in making this work. - How the design relates to the Liskov Substitution Principle.
Provide the code and a clear explanation of your design choices.
Hints
Hint 1
Give each strategy a bean name through its stereotype annotation. When Spring injects a Map whose value type is your interface, it uses bean names as the keys.
Hint 2
The dispatcher should do one lookup and one null check, then delegate. It should never mention a concrete strategy class.
Hint 3
Think about what a caller must be able to assume about any PaymentStrategy, and where input validation should live so that no implementation tightens the contract.
Hint 4
Bean names become part of your public API. Consider what happens if someone renames a class, and whether an explicit type identifier on the interface would be safer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the Strategy pattern combined with Spring's collection injection. Each payment method is a separate bean behind a shared interface. Spring builds the registry (a Map<String, PaymentStrategy>), and the service only looks up and delegates. Adding a method means adding a class, not editing the dispatcher.
Code
public interface PaymentStrategy {
/** Charges the given amount. Callers may rely on this contract for every implementation. */
void processPayment(double amount);
}
import org.springframework.stereotype.Component;
@Component("creditCard")
public class CreditCardPayment implements PaymentStrategy {
@Override
public void processPayment(double amount) {
// Real system: authorize and capture through a card gateway
System.out.printf("Charged %.2f to credit card%n", amount);
}
}
import org.springframework.stereotype.Component;
@Component("crypto")
public class CryptoPayment implements PaymentStrategy {
@Override
public void processPayment(double amount) {
// Real system: create an invoice and wait for on-chain confirmation
System.out.printf("Paid %.2f with crypto%n", amount);
}
}
import java.util.Map;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private final Map<String, PaymentStrategy> strategies;
// Spring injects every PaymentStrategy bean, keyed by bean name
public PaymentService(Map<String, PaymentStrategy> strategies) {
this.strategies = Map.copyOf(strategies);
}
public void executePayment(String type, double amount) {
if (type == null) {
throw new IllegalArgumentException("Payment type must not be null");
}
PaymentStrategy strategy = strategies.get(type);
if (strategy == null) {
throw new IllegalArgumentException(
"Unknown payment type: " + type + ". Supported: " + strategies.keySet());
}
strategy.processPayment(amount);
}
}
The null check comes first because maps created by Map.copyOf throw NullPointerException on get(null). Checking up front means every bad type produces an IllegalArgumentException, as the requirement states.
How this answers the discussion points
Open/Closed Principle. PaymentService knows only the interface and a map that Spring assembles at startup. A new PayPalPayment annotated with @Component("payPal") is picked up automatically, and no existing class changes. The system is open for extension and closed for modification.
Map versus if-else or switch.
- A conditional chain must be edited for every new method, and the service becomes coupled to every concrete class.
- The map gives O(1) lookup, and the bean registry is the single source of truth for what is supported.
- Strategies can be unit-tested in isolation. The service can be tested with a hand-built map and no Spring context.
- The unknown-type case is handled in one place (a null result) rather than a final
elsethat is easy to forget.
Spring wiring.
- When you inject
Map<String, T>, Spring collects all beans of typeTand uses bean names as keys. This is why@Component("creditCard")matters: the name is the lookup key. - Injecting a
List<PaymentStrategy>also collects all beans and supports ordering with@Order. @Qualifierselects one specific bean when you inject a single dependency. Here we need all strategies, so collection injection is the right tool, and the explicit bean names play the role of qualifiers.
Liskov Substitution Principle. Any PaymentStrategy must be usable wherever the interface is expected. That means:
- No implementation may add a stricter precondition than the interface documents. Shared checks, such as rejecting non-positive or
NaNamounts, are best done once in the service or documented on the interface. - No implementation may throw unexpected exception types. Use a documented payment exception for business failures.
- If a method needs different inputs (card token versus wallet address), do not add nullable fields to the shared method. Introduce a request type instead, for example
processPayment(PaymentRequest request)with a sealed hierarchy of request records.
A sturdier variant
Bean names double as public identifiers, so renaming a class or changing a name could silently break clients. A safer design adds String type() to the interface, injects a List<PaymentStrategy>, and builds the map explicitly:
this.strategies = strategies.stream()
.collect(Collectors.toUnmodifiableMap(PaymentStrategy::type, s -> s));
toUnmodifiableMap throws on duplicate keys, so two strategies claiming the same type fail at startup instead of one silently shadowing the other. The cost is a little more code and a method on the interface.
Complexity
- Startup: O(n) to build the map for n strategies.
- Each
executePaymentcall: O(1) for the lookup, plus the cost of the strategy itself. - Space: O(n) for the map. Strategies are singleton beans, so the dispatcher allocates nothing per request.
Edge cases and trade-offs
- Null or unknown type: throw
IllegalArgumentException, ideally listing supported keys in the message. - Case sensitivity:
"CreditCard"does not match"creditCard". Either document exact keys or normalize both keys and input (for example lowercase). - Duplicate bean names: Spring rejects conflicting definitions at startup, which is the fail-fast behavior you want.
- Invalid amounts: zero, negative, and
NaNvalues should be rejected centrally rather than in each strategy. - No strategies registered: a required collection with no matching beans fails at startup, which is usually right for a payment service.
- Money as
double: acceptable for this exercise, but production code should useBigDecimalor integer minor units together with a currency, to avoid rounding errors. - Constructor versus field injection: prefer constructor injection. It allows
finalfields, makes dependencies explicit, and lets you build the service in a plain unit test.
Common mistakes
- Injecting a raw
Mapand casting, instead ofMap<String, PaymentStrategy>. - Keeping a
switch"just for unknown types" or for special cases, which reintroduces the coupling you were trying to remove. - Forgetting that bean names are the keys, and then wondering why lookups return null (for example, a default name of
creditCardPaymentinstead ofcreditCard). - Letting each strategy re-validate or reinterpret shared inputs differently, which breaks substitutability.
- Using
@Qualifierto pick strategies inside the service, which hard-codes the list of methods and defeats the Open/Closed goal.