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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A sealed interface with Jackson subtypes lets one endpoint accept several concrete shapes while keeping the type set closed and exhaustive.
- 2Records make immutable DTOs concise, and validation annotations on their components enforce per-type rules automatically.
- 3Combining @Valid with polymorphic binding means each incoming payment method is validated against only its own constraints.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/polymorphic-payment-requests-in-spring-explained-java-e6a9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.