java 47 lines · 7 steps

Polymorphic payment requests in Spring

A Spring REST endpoint deserializes and validates one of several payment types using a sealed interface and Jackson subtype resolution.

Explained by highlit
1@RestController
2@RequestMapping("/api/payments")
3public class PaymentController {
4 
5 private final PaymentProcessor processor;
6 
7 public PaymentController(PaymentProcessor processor) {
8 this.processor = processor;
9 }
10 
11 @PostMapping
12 public ResponseEntity<PaymentReceipt> submit(@Valid @RequestBody PaymentRequest request) {
13 PaymentReceipt receipt = processor.charge(request);
14 return ResponseEntity.status(HttpStatus.CREATED).body(receipt);
15 }
16 
17 @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "method", visible = true)
18 @JsonSubTypes({
19 @JsonSubTypes.Type(value = CardPayment.class, name = "card"),
20 @JsonSubTypes.Type(value = BankTransferPayment.class, name = "bank_transfer"),
21 @JsonSubTypes.Type(value = WalletPayment.class, name = "wallet")
22 })
23 public sealed interface PaymentRequest permits CardPayment, BankTransferPayment, WalletPayment {
24 String method();
25 long amountCents();
26 }
27 
28 public record CardPayment(
29 @NotNull String method,
30 @Positive long amountCents,
31 @NotBlank @Pattern(regexp = "\\d{16}") String cardNumber,
32 @NotBlank String expiry) implements PaymentRequest {
33 }
34 
35 public record BankTransferPayment(
36 @NotNull String method,
37 @Positive long amountCents,
38 @NotBlank String iban,
39 @NotBlank String accountHolder) implements PaymentRequest {
40 }
41 
42 public record WalletPayment(
43 @NotNull String method,
44 @Positive long amountCents,
45 @NotBlank String walletId) implements PaymentRequest {
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A sealed interface with Jackson subtypes lets one endpoint accept several concrete shapes while keeping the type set closed and exhaustive.
  2. 2Records make immutable DTOs concise, and validation annotations on their components enforce per-type rules automatically.
  3. 3Combining @Valid with polymorphic binding means each incoming payment method is validated against only its own constraints.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Polymorphic payment requests in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code