今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

OrderHub Day 4: Bean Validation + Clean DTOs (Spring Boot)

Devanshu Biswas 2026年06月23日 14:17 3 次阅读 来源:Dev.to

OrderHub Day 4: never trust the client. Today the backend gets proper Bean Validation — bad requests are rejected at the edge with a clear 400, long before they reach the business logic. And it's all declarative. ✅ Try the validating form (see the 400 body): https://dev48v.infy.uk/orderhub/day4-validation.html Three DTOs, three jobs A common beginner mistake is using one class everywhere. OrderHub keeps them separate: Request DTO ( CreateOrderRequest ) — what the client sends, and where validation lives. Domain/Entity ( Order ) — the internal model. Response DTO ( OrderResponse ) — what the API returns, so internal fields never leak. Validation is just annotations public record CreateOrderRequest ( @NotBlank @Size ( max = 120 ) @CleanText String customer , @NotBlank @Size ( max = 200 ) @CleanText String item , @Min ( 1 ) @Max ( 1000 ) int quantity ) {} Add @Valid @RequestBody on the controller and Spring checks every rule before your method runs. Break one and it throws MethodArgumentNotValidException . A custom constraint + clean errors @CleanText is a custom ConstraintValidator (rejects blank-after-trim + a small blocklist) — you can write your own rules, not just the built-ins. A @RestControllerAdvice turns validation failures into a tidy 400 with a field→message map. (Day 5 upgrades this to full RFC-7807 ProblemDetail.) 🔨 Full walkthrough (constraints → @valid → custom validator → 400 handler) on the page: https://dev48v.infy.uk/orderhub/day4-validation.html OrderHub — a production-grade Spring Boot backend, one feature a day. 🌐 https://dev48v.infy.uk · Code: https://github.com/dev48v/order-hub-from-zero

本文内容来源于互联网,版权归原作者所有
查看原文