Spring Payment Strategy Service Design
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Design a pluggable checkout billing module in Java and Spring where new payment rails can be introduced as standalone beans without editing core dispatch code.
Your implementation must satisfy these specifications:
- Declare a
PaymentStrategyinterface exposingprocessPayment(double amount). - Provide two Spring-managed implementations:
CreditCardPaymentandCryptoPayment. - Implement a
PaymentServicecomponent whoseMap<String, PaymentStrategy>registry is populated automatically by Spring dependency injection from the application context. - Expose
executePayment(String type, double amount)onPaymentServiceto look up the requested strategy key and invokeprocessPayment(amount). ThrowIllegalArgumentExceptionwhenevertypedoes not match a registered strategy or inputs are invalid.
// Spring-wired service instance
PaymentService service = ...;
// Dispatches to the "creditCard" strategy bean for $240.00
service.executePayment("creditCard", 240.0);
Scope & Expectations
- SOLID contracts: Keep
PaymentServiceopen for extension via new@Componentbeans without modifying existing service logic (Open/Closed Principle), and define a consistent behavioral contract across subtypes (Liskov Substitution Principle). - Dispatch mechanics: Justify dictionary-backed strategy lookup over multi-branch
if-elseorswitchchains as the number of payment providers grows. - Spring wiring: Show how bean naming, constructor-injected
Mapcollection autowiring, and@Qualifierannotations work together cleanly, and guard boundary inputs (nullkeys, non-positive or non-finite amounts).
Step-by-step walkthrough
Architecture and the Liskov Substitution contract
The Strategy pattern encapsulates interchangeable algorithms behind one shared interface so callers select behavior at runtime without knowing concrete class details. Paired with Spring's dependency injection,
PaymentServicenever instantiates or imports any payment class—Spring discovers every strategy bean at startup and populates an immutableMap<String, PaymentStrategy>registry automatically:Naive switch/if-else (tightly coupled — every new method edits PaymentService): PaymentService ---> if ("creditCard") new CreditCardPayment() ---> else if ("crypto") new CryptoPayment() Strategy + Spring Map injection (decoupled — adding Apple Pay edits zero existing files): @Component("creditCard") CreditCardPayment --\ @Component("crypto") CryptoPayment ---+--> Map<String, PaymentStrategy> ---> PaymentService @Component("applePay") ApplePayPayment --/ (built by Spring at startup) .executePayment(type, amount)Before writing code, pin down the behavioral contract every implementation must obey. That is the Liskov Substitution Principle (LSP) (any implementation of
PaymentStrategymust be safely usable whereverPaymentStrategyis expected, without surprising the caller):- Preconditions cannot be strengthened: If
PaymentStrategyaccepts any finiteamount > 0, a concrete strategy likeCryptoPaymentcannot suddenly throw an undeclaredUnsupportedOperationExceptionwhenamountis$0.25. - Business declines are normal return values, not surprise exceptions: Returning a small
PaymentResultrecord withapproved = falselets every strategy report business refusals (card declined, below blockchain fee threshold) uniformly, while callers likeservice.executePayment("creditCard", 240.0);can still ignore the return value if they choose. - Lookup keys match explicit bean names: Passing
"creditCard"looks up the bean named"creditCard".
One practical note worth mentioning in interviews: the required signature uses
doublefor money, and binary floating-point arithmetic cannot represent most base-10 decimals exact to the cent (0.1 + 0.2 == 0.30000000000000004). We keepdoublestrictly to honor the prompt's signature; real payment systems useBigDecimalor alongcount of minor units (cents).- Preconditions cannot be strengthened: If
Define the PaymentStrategy interface and PaymentResult
A compact Java
record(Java 16+) carries the outcome cleanly, and Javadoc onPaymentStrategyspells out the exact contract that every current and future payment method must keep:public record PaymentResult( String type, double amount, boolean approved, String detail ) {}public interface PaymentStrategy { /** * Processes a payment for the given positive, finite amount. * * Precondition: amount is finite and strictly greater than 0 (validated by PaymentService). * Contract: implementations must handle every valid amount without throwing undeclared * business-rule exceptions; declines (such as insufficient funds or provider minimums) * are returned with approved == false. */ PaymentResult processPayment(double amount); }Putting the rules on the interface makes LSP verifiable: anyone adding a tenth payment method immediately sees what inputs must be accepted and how refusals are communicated.
Implement CreditCardPayment and CryptoPayment as named Spring beans
Annotate each concrete strategy with
@Component("<key>")so Spring registers it under the exact lookup key callers pass toexecutePayment:import java.util.UUID; import org.springframework.stereotype.Component; @Component("creditCard") public class CreditCardPayment implements PaymentStrategy { @Override public PaymentResult processPayment(double amount) { // Production code delegates to an injected card-gateway client here. String reference = "card-" + UUID.randomUUID(); return new PaymentResult("creditCard", amount, true, reference); } }import java.util.UUID; import org.springframework.stereotype.Component; @Component("crypto") public class CryptoPayment implements PaymentStrategy { static final double MINIMUM_AMOUNT = 1.00; // Network fees make sub-dollar transfers uneconomical @Override public PaymentResult processPayment(double amount) { if (amount < MINIMUM_AMOUNT) { return new PaymentResult( "crypto", amount, false, "Below crypto minimum of " + MINIMUM_AMOUNT ); } String reference = "crypto-" + UUID.randomUUID(); return new PaymentResult("crypto", amount, true, reference); } }Three details do real engineering work here:
- Explicit bean names (
"creditCard","crypto"): Without"creditCard", Spring derives the default bean name by lower-casing the first letter of the class name—producing"creditCardPayment", which would causeexecutePayment("creditCard", 240.0)to fail withIllegalArgumentExceptioneven though the bean exists! - LSP preservation:
CryptoPaymentenforces its$1.00minimum by returningapproved = falseinstead of throwing an unexpected exception, soPaymentServicenever needs specialtry/catchorinstanceoflogic for crypto. - Stateless singletons: Spring beans are singletons by default (one shared instance across all request threads), so neither strategy stores per-payment data in instance fields.
- Explicit bean names (
Wire the strategy Map automatically in PaymentService
When a Spring bean's constructor declares
Map<String, PaymentStrategy>, Spring collects everyPaymentStrategybean in theApplicationContextand injects a map whose keys are bean names and whose values are the bean instances:Injected constructor map at startup: { "creditCard" -> CreditCardPayment singleton, "crypto" -> CryptoPayment singleton }import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import org.springframework.stereotype.Service; @Service public class PaymentService { private final Map<String, PaymentStrategy> strategies; // Single constructor: Spring 4.3+ injects all PaymentStrategy beans keyed by bean name public PaymentService(Map<String, PaymentStrategy> strategies) { Objects.requireNonNull(strategies, "strategies map must not be null"); if (strategies.isEmpty()) { throw new IllegalArgumentException("At least one PaymentStrategy must be provided"); } // Freeze into an unmodifiable copy so nothing can mutate the registry after construction this.strategies = Map.copyOf(strategies); } public PaymentResult executePayment(String type, double amount) { // Check type == null BEFORE containsKey, because Map.copyOf maps throw NullPointerException on null keys if (type == null || !strategies.containsKey(type)) { throw new IllegalArgumentException( "Unknown payment type '" + type + "'. Supported types: " + new TreeSet<>(strategies.keySet()) ); } // Double.isFinite rejects NaN and +/-Infinity; (amount <= 0) alone lets NaN slip through! if (!Double.isFinite(amount) || amount <= 0.0) { throw new IllegalArgumentException("Payment amount must be finite and > 0, got: " + amount); } PaymentStrategy strategy = strategies.get(type); return strategy.processPayment(amount); } public Set<String> supportedTypes() { return strategies.keySet(); } }Trace five calls to verify every boundary condition:
Call Outcome ---------------------------------------- ------------------------------------------------------------------ executePayment("creditCard", 240.0) -> PaymentResult[type=creditCard, amount=240.0, approved=true, ...] executePayment("crypto", 0.25) -> PaymentResult[type=crypto, amount=0.25, approved=false, ...] executePayment("applePay", 80.0) -> IllegalArgumentException: Unknown payment type 'applePay'... executePayment(null, 80.0) -> IllegalArgumentException (NOT NullPointerException!) executePayment("creditCard", Double.NaN) -> IllegalArgumentException (NaN <= 0 is false, caught by isFinite)Open/Closed extension, Map vs. switch, and @Qualifier
Open/Closed Principle (OCP) in action: Supporting Apple Pay requires adding one new file and touching zero lines in
PaymentService:import java.util.UUID; import org.springframework.stereotype.Component; @Component("applePay") public class ApplePayPayment implements PaymentStrategy { @Override public PaymentResult processPayment(double amount) { String reference = "applepay-" + UUID.randomUUID(); return new PaymentResult("applePay", amount, true, reference); } }On the next application boot, Spring automatically adds
"applePay" -> ApplePayPaymentintoPaymentService's map.Why a
Mapbeatsif-elseorswitch: The real win is architectural decoupling, not raw CPU speed (hashing a key vs. comparing three strings takes nanoseconds either way). AswitchinsidePaymentServiceforcesPaymentServiceto import every concrete payment class, creates Git merge conflicts whenever two teams add payment methods simultaneously, and requires modifying and retesting core dispatch code for every addition.How
@Qualifierfits in: Every bean's name doubles as its default qualifier:- When
PaymentServicewants all strategies dynamically by runtime string,Map<String, PaymentStrategy>autowires the entire family with zero@Qualifierboilerplate. - When another service (such as
CardChargebackWorker) always needs one specific strategy, injecting barePaymentStrategyfails at startup withNoUniqueBeanDefinitionExceptionbecause multiple beans match; adding@Qualifier("creditCard") PaymentStrategy cardStrategypicks the exact bean cleanly.
Optional production hardening (decoupling keys from bean names): Relying on
@Component("creditCard")ties wire-protocol strings to Spring metadata. A sturdier variation addsString paymentType()toPaymentStrategy, injectsList<PaymentStrategy>into the constructor, and builds the map explicitly while failing fast on duplicate keys:public PaymentService(List<PaymentStrategy> strategyBeans) { Map<String, PaymentStrategy> registry = new HashMap<>(); for (PaymentStrategy strategy : strategyBeans) { PaymentStrategy existing = registry.put(strategy.paymentType(), strategy); if (existing != null) { throw new IllegalStateException("Duplicate strategy for type: " + strategy.paymentType()); } } this.strategies = Map.copyOf(registry); }- When
Unit test in plain Java and verify Spring wiring
Because
PaymentServiceuses constructor injection, 95% of your tests run in milliseconds using plain JUnit 5 andMap.of(...)with no Spring container overhead:import static org.junit.jupiter.api.Assertions.*; import java.util.Map; import org.junit.jupiter.api.Test; class PaymentServiceTest { private final PaymentService service = new PaymentService(Map.of( "creditCard", new CreditCardPayment(), "crypto", new CryptoPayment() )); @Test void routesKnownTypeToMatchingStrategy() { PaymentResult result = service.executePayment("creditCard", 240.0); assertTrue(result.approved()); assertEquals("creditCard", result.type()); assertEquals(240.0, result.amount()); } @Test void throwsIllegalArgumentOnUnknownOrNullType() { assertThrows(IllegalArgumentException.class, () -> service.executePayment("applePay", 50.0)); assertThrows(IllegalArgumentException.class, () -> service.executePayment(null, 50.0)); } @Test void rejectsNonPositiveAndNonFiniteAmounts() { assertThrows(IllegalArgumentException.class, () -> service.executePayment("creditCard", 0.0)); assertThrows(IllegalArgumentException.class, () -> service.executePayment("creditCard", -15.0)); assertThrows(IllegalArgumentException.class, () -> service.executePayment("creditCard", Double.NaN)); } @Test void declinesCryptoBelowMinimumWithoutBreakingLsp() { PaymentResult result = service.executePayment("crypto", 0.25); assertFalse(result.approved()); } }Pair those fast unit tests with one small
@SpringJUnitConfigintegration check verifying that@Component("creditCard")and@Component("crypto")register under the expected bean names:import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig(classes = {PaymentService.class, CreditCardPayment.class, CryptoPayment.class}) class PaymentSpringWiringTest { @Autowired private PaymentService service; @Test void populatesMapWithExplicitBeanNames() { assertEquals(Set.of("creditCard", "crypto"), service.supportedTypes()); } }
Intuition & how it works
Think of PaymentService as a universal checkout terminal with labeled plug-in slots ("creditCard", "crypto", "applePay"). Instead of soldering every payment provider directly onto the terminal's main board, the Strategy pattern (an object-oriented pattern that puts interchangeable algorithms behind one shared interface) defines a standard plug shape (PaymentStrategy), and Dependency Injection (where the Spring framework constructs objects and passes them into your class rather than your code calling new) automatically discovers every compatible plug at application startup and places it into an immutable Map<String, PaymentStrategy> directory keyed by its bean name.
The obvious alternative—writing if ("creditCard".equals(type)) ... else if ("crypto".equals(type)) ... directly inside PaymentService—falls apart as soon as the team grows. Every new payment method forces edits to PaymentService, violating the Open/Closed Principle (software should accept new behavior via new classes without modifying tested code), coupling core checkout logic to every third-party SDK, and creating constant merge conflicts. Even with Spring's map injection, skipping explicit bean names (@Component defaulting CreditCardPayment to "creditCardPayment") or skipping null and NaN guards breaks runtime dispatch with unexpected NullPointerExceptions or corrupted amounts.
Walk through startup and three concrete calls:
1. Startup wiring: Spring scans @Component("creditCard") CreditCardPayment and @Component("crypto") CryptoPayment as singleton beans (one shared instance per class across the JVM) and passes {"creditCard": CreditCardPayment, "crypto": CryptoPayment} into PaymentService's constructor, which freezes the map with Map.copyOf.
2. Approved payment: executePayment("creditCard", 240.0) validates that "creditCard" is non-null and registered and 240.0 is finite and positive, then delegates to CreditCardPayment, returning PaymentResult[approved=true, amount=240.0].
3. Provider-specific decline honoring Liskov Substitution: executePayment("crypto", 0.25) routes to CryptoPayment, which sees 0.25 < 1.00 and returns PaymentResult[approved=false] rather than throwing an undeclared exception—honoring the Liskov Substitution Principle (every subtype behaves consistently with the base interface's contract).
4. Invalid key rejection: executePayment("wireTransfer", 80.0) or executePayment(null, 80.0) fails fast at the service boundary with a clear IllegalArgumentException listing the supported keys [creditCard, crypto].
Key points
- Strategy + registry decoupling:
PaymentServicedepends solely on thePaymentStrategyabstraction, never importing any concrete payment implementation (satisfying Dependency Inversion and Open/Closed simultaneously). - Spring
Map<String, T>autowiring: DeclaringMap<String, PaymentStrategy>in a single constructor causes Spring to inject allPaymentStrategybeans keyed by bean name; always specify explicit names like@Component("creditCard")(or build the map from an injectedList<PaymentStrategy>using apaymentType()method) so class renames never silently change API keys. - Explicit Liskov Substitution contract: Document valid inputs (
amountfinite and> 0) onPaymentStrategyand represent business refusals (declined cards, fee minimums) as structuredPaymentResultvalues rather than surprise implementation-specific exceptions. - Defensive boundary validation: Guard
type == nullbefore callingstrategies.containsKey(type)(immutable maps fromMap.copyOfthrowNullPointerExceptiononnullkeys), and validateDouble.isFinite(amount) && amount > 0becauseDouble.NaN <= 0evaluates tofalse. @Qualifiervs. map injection: UseMap<String, PaymentStrategy>when selecting strategies dynamically by runtime input; use@Qualifier("creditCard") PaymentStrategywhen a caller statically needs one specific implementation without triggeringNoUniqueBeanDefinitionException.- Money representation: Keep
doubleonly when mandated by an existing interface (0.1 + 0.2 == 0.30000000000000004); useBigDecimalor integer minor units (long cents) in real financial systems.
Common mistakes
- Forgetting explicit bean names on
@Component:@ComponentonCreditCardPaymentregisters bean key"creditCardPayment", causingexecutePayment("creditCard", 240.0)to throwIllegalArgumentExceptionat runtime. - Passing
nullintoMap.copyOf(...).get(type)orcontainsKey(type): Unmodifiable maps created byMap.copyOforMap.ofrejectnullkeys withNullPointerExceptioninstead of returningfalseornull, violating the requirement to throwIllegalArgumentException. - Checking only
if (amount <= 0): In IEEE-754 floating point, every comparison againstDouble.NaNreturnsfalse, soNaNslips right pastamount <= 0into downstream billing calls unless!Double.isFinite(amount)is checked too. - Breaking Liskov Substitution with surprise exceptions or
instanceofchecks: Having one strategy throwUnsupportedOperationExceptionon small amounts—or addingif (strategy instanceof CryptoPayment)insidePaymentService—destroys polymorphism and forces callers to know about concrete subtypes. - Storing per-request state in strategy fields: Because Spring beans default to singleton scope, saving
this.currentAmount = amountinsideCreditCardPaymentcauses concurrent HTTP threads to overwrite each other's payments.
Follow-up questions
- What changes would you make if different payment providers needed distinct request fields rather than just a numeric amount? Replace the bare
double amountparameter with a polymorphic request hierarchy—for example, a Java 17 sealed interface (an interface that restricts which classes may implement it)PaymentRequestwith commonamount()/currency()fields implemented by method-specific records likeCardPaymentRequest(double amount, String cardToken)andCryptoPaymentRequest(double amount, String walletAddress, String network). Avoid adding every conceivable parameter to one bloated method signature (which violates Interface Segregation) or passing an untypedMap<String, Object>(which sacrifices compile-time safety). EachPaymentStrategy<R extends PaymentRequest>then declaresClass<R> supportedRequestType()andPaymentResult processPayment(R request), allowingPaymentServiceto route safely byrequest.getClass().
```java public sealed interface PaymentRequest permits CardRequest, CryptoRequest { double amount(); } public record CardRequest(double amount, String cardToken) implements PaymentRequest {} public record CryptoRequest(double amount, String walletAddress) implements PaymentRequest {}
public interface TypedPaymentStrategy
-
Why is constructor injection preferred over field injection when wiring the strategy registry, and what are the trade-offs? Constructor injection lets
strategiesbeprivate finaland wrapped inMap.copyOf(...), guaranteesPaymentServicecan never be instantiated in a half-initialized state, surfaces circular dependencies immediately at startup, and lets plain JUnit tests callnew PaymentService(Map.of(...))in milliseconds without booting Spring or using reflection. Field injection (@Autowired private Map<String, PaymentStrategy> strategies;) saves a few lines of boilerplate, but forbidsfinalfields, leavesstrategiesasnullwhenever someone callsnew PaymentService()outside Spring, requires reflection or a full Spring context in unit tests, and makes dependency bloat harder to spot—which is why the Spring team recommends constructor injection for all required dependencies. -
If a payment strategy needed to track mutable per-transaction state, how would you keep concurrent executions thread-safe in Spring? Keep the
PaymentStrategysingleton itself completely stateless and encapsulate per-transaction mutable state (retry counters, authorization tokens, step timestamps) inside a fresh helper object allocated as a local variable insideprocessPayment(...), so each request thread owns its own isolated instance with zero locking overhead. If that per-transaction helper genuinely needs Spring-managed dependencies, register it with@Scope("prototype")and request a fresh instance per call viaObjectProvider<TransactionContext>.getObject()(never inject a prototype bean directly into a singleton field, which captures only one instance forever). AvoidsynchronizedonprocessPayment(which serializes all concurrent checkouts for that payment method) and avoidThreadLocal(which leaks state across pooled threads if cleanup is missed and breaks across async hops); for cross-node state like idempotency keys (unique client tokens preventing duplicate charges on network retries), persist state in a database with a unique constraint rather than in JVM memory.
Follow-up questions
- What changes would you make if different payment providers needed distinct request fields rather than just a numeric amount?
- Why is constructor injection preferred over field injection when wiring the strategy registry, and what are the trade-offs?
- If a payment strategy needed to track mutable per-transaction state, how would you keep concurrent executions thread-safe in Spring?
Similar questions
- Backend Java and Spring Framework Essentials
- Count Characters by First Appearance
- Longest Duplicate-Free Substring
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination