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 PaymentStrategy interface exposing processPayment(double amount).
  • Provide two Spring-managed implementations: CreditCardPayment and CryptoPayment.
  • Implement a PaymentService component whose Map<String, PaymentStrategy> registry is populated automatically by Spring dependency injection from the application context.
  • Expose executePayment(String type, double amount) on PaymentService to look up the requested strategy key and invoke processPayment(amount). Throw IllegalArgumentException whenever type does 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 PaymentService open for extension via new @Component beans 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-else or switch chains as the number of payment providers grows.
  • Spring wiring: Show how bean naming, constructor-injected Map collection autowiring, and @Qualifier annotations work together cleanly, and guard boundary inputs (null keys, non-positive or non-finite amounts).

Step-by-step walkthrough

  1. 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, PaymentService never instantiates or imports any payment class—Spring discovers every strategy bean at startup and populates an immutable Map<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 PaymentStrategy must be safely usable wherever PaymentStrategy is expected, without surprising the caller):

    • Preconditions cannot be strengthened: If PaymentStrategy accepts any finite amount > 0, a concrete strategy like CryptoPayment cannot suddenly throw an undeclared UnsupportedOperationException when amount is $0.25.
    • Business declines are normal return values, not surprise exceptions: Returning a small PaymentResult record with approved = false lets every strategy report business refusals (card declined, below blockchain fee threshold) uniformly, while callers like service.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 double for money, and binary floating-point arithmetic cannot represent most base-10 decimals exact to the cent (0.1 + 0.2 == 0.30000000000000004). We keep double strictly to honor the prompt's signature; real payment systems use BigDecimal or a long count of minor units (cents).

  2. Define the PaymentStrategy interface and PaymentResult

    A compact Java record (Java 16+) carries the outcome cleanly, and Javadoc on PaymentStrategy spells 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.

  3. 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 to executePayment:

    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 cause executePayment("creditCard", 240.0) to fail with IllegalArgumentException even though the bean exists!
    • LSP preservation: CryptoPayment enforces its $1.00 minimum by returning approved = false instead of throwing an unexpected exception, so PaymentService never needs special try/catch or instanceof logic 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.
  4. Wire the strategy Map automatically in PaymentService

    When a Spring bean's constructor declares Map<String, PaymentStrategy>, Spring collects every PaymentStrategy bean in the ApplicationContext and 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)
    
  5. 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" -> ApplePayPayment into PaymentService's map.

    Why a Map beats if-else or switch: The real win is architectural decoupling, not raw CPU speed (hashing a key vs. comparing three strings takes nanoseconds either way). A switch inside PaymentService forces PaymentService to 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 @Qualifier fits in: Every bean's name doubles as its default qualifier:

    • When PaymentService wants all strategies dynamically by runtime string, Map<String, PaymentStrategy> autowires the entire family with zero @Qualifier boilerplate.
    • When another service (such as CardChargebackWorker) always needs one specific strategy, injecting bare PaymentStrategy fails at startup with NoUniqueBeanDefinitionException because multiple beans match; adding @Qualifier("creditCard") PaymentStrategy cardStrategy picks 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 adds String paymentType() to PaymentStrategy, injects List<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);
    }
    
  6. Unit test in plain Java and verify Spring wiring

    Because PaymentService uses constructor injection, 95% of your tests run in milliseconds using plain JUnit 5 and Map.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 @SpringJUnitConfig integration 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: PaymentService depends solely on the PaymentStrategy abstraction, never importing any concrete payment implementation (satisfying Dependency Inversion and Open/Closed simultaneously).
  • Spring Map<String, T> autowiring: Declaring Map<String, PaymentStrategy> in a single constructor causes Spring to inject all PaymentStrategy beans keyed by bean name; always specify explicit names like @Component("creditCard") (or build the map from an injected List<PaymentStrategy> using a paymentType() method) so class renames never silently change API keys.
  • Explicit Liskov Substitution contract: Document valid inputs (amount finite and > 0) on PaymentStrategy and represent business refusals (declined cards, fee minimums) as structured PaymentResult values rather than surprise implementation-specific exceptions.
  • Defensive boundary validation: Guard type == null before calling strategies.containsKey(type) (immutable maps from Map.copyOf throw NullPointerException on null keys), and validate Double.isFinite(amount) && amount > 0 because Double.NaN <= 0 evaluates to false.
  • @Qualifier vs. map injection: Use Map<String, PaymentStrategy> when selecting strategies dynamically by runtime input; use @Qualifier("creditCard") PaymentStrategy when a caller statically needs one specific implementation without triggering NoUniqueBeanDefinitionException.
  • Money representation: Keep double only when mandated by an existing interface (0.1 + 0.2 == 0.30000000000000004); use BigDecimal or integer minor units (long cents) in real financial systems.

Common mistakes

  • Forgetting explicit bean names on @Component: @Component on CreditCardPayment registers bean key "creditCardPayment", causing executePayment("creditCard", 240.0) to throw IllegalArgumentException at runtime.
  • Passing null into Map.copyOf(...).get(type) or containsKey(type): Unmodifiable maps created by Map.copyOf or Map.of reject null keys with NullPointerException instead of returning false or null, violating the requirement to throw IllegalArgumentException.
  • Checking only if (amount <= 0): In IEEE-754 floating point, every comparison against Double.NaN returns false, so NaN slips right past amount <= 0 into downstream billing calls unless !Double.isFinite(amount) is checked too.
  • Breaking Liskov Substitution with surprise exceptions or instanceof checks: Having one strategy throw UnsupportedOperationException on small amounts—or adding if (strategy instanceof CryptoPayment) inside PaymentService—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 = amount inside CreditCardPayment causes 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 amount parameter with a polymorphic request hierarchy—for example, a Java 17 sealed interface (an interface that restricts which classes may implement it) PaymentRequest with common amount()/currency() fields implemented by method-specific records like CardPaymentRequest(double amount, String cardToken) and CryptoPaymentRequest(double amount, String walletAddress, String network). Avoid adding every conceivable parameter to one bloated method signature (which violates Interface Segregation) or passing an untyped Map<String, Object> (which sacrifices compile-time safety). Each PaymentStrategy<R extends PaymentRequest> then declares Class<R> supportedRequestType() and PaymentResult processPayment(R request), allowing PaymentService to route safely by request.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 { Class requestType(); PaymentResult processPayment(R request); } ```

  • Why is constructor injection preferred over field injection when wiring the strategy registry, and what are the trade-offs? Constructor injection lets strategies be private final and wrapped in Map.copyOf(...), guarantees PaymentService can never be instantiated in a half-initialized state, surfaces circular dependencies immediately at startup, and lets plain JUnit tests call new 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 forbids final fields, leaves strategies as null whenever someone calls new 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 PaymentStrategy singleton 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 inside processPayment(...), 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 via ObjectProvider<TransactionContext>.getObject() (never inject a prototype bean directly into a singleton field, which captures only one instance forever). Avoid synchronized on processPayment (which serializes all concurrent checkouts for that payment method) and avoid ThreadLocal (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

Similar questions

More Antra interview questions

All 4 Antra questions →