【问题标题】:How can i validate dto of type record in spring framework?我如何在 spring 框架中验证记录类型的 dto?
【发布时间】:2022-12-15 22:23:18
【问题描述】:

我有一个端点来创建 Seller 对象。我从记录类型的 dto 中获取了创建 Seller 对象的必要信息。 我如何在 spring 验证中验证这个 dto?我需要确保传入的 DTO 对象的数据经过验证。我不想手动验证。

@RestController
@RequestMapping("api/sellers")
public class SellerController {

    private final SellerService sellerService;
    private final CreateSellerRequestValidator createSellerRequestValidator;

    @PostMapping
    public ResponseEntity<?> create(@RequestBody CreateSellerRequestDTO createSellerRequestDTO){
            createSellerRequestValidator.validate(createSellerRequestDTO);
            sellerService.create(createSellerRequestDTO);
            return ResponseEntity.ok().build();
    }
}
public record CreateSellerRequestDTO(String createdBy,
                                     String userName,
                                     String name,
                                     String email,
                                     BigDecimal shippingCost,
                                     String password,
                                     SellerAddress sellerAddress) {
}

【问题讨论】:

  • 您的记录需要有验证注释,例如 @NotNull String createdBy 然后在您的控制器中 @RequestBody @Valid CreateSellerRequestDTO 尽管这是一条记录,但我不太确定它是否有效。试试看

标签: java spring spring-boot spring-validator


【解决方案1】:

像这样尝试:

public record CreateSellerRequestDTO(@NotNull(message = "createdBy can not be null") String createdBy,
                                     @NotNull(message = "userName can not be null") String userName,
                                     String name,
                                     String email,
                                     BigDecimal shippingCost,
                                     String password,
                                     SellerAddress sellerAddress) {

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多