Spring 当对象为 null/empty 时引导 rest requestbody 和 @valid 不工作

Spring boot rest requestbody and @valid not working when object is null/empty

我正在尝试对我的请求的 instructedAmount 属性应用非空验证,但它不起作用。我有一个 Spring Boot (V2.3.0.RELEASE) 应用程序,具有以下端点:

@Validated
public class TestController {
@PostMapping(value = "/test/pay")
    public ResponseEntity<IPSPaymentResponse> validatePayt(@Valid @RequestBody InstantPaymentRequest instantPaymentRequest) {
        log.debug("start validatePayment method {}", instantPaymentRequest);
....

InstantPaymentRequest如下:

@Data
@Validated
public class InstantPaymentRequest {
    @Valid
    private PaymentIdentificationRequest paymentIdentification;
    @NotBlank(message = "transactionTypeCode.required")
    private String transactionTypeCode;
    @Valid
    private InstructedAmount instructedAmount;
    @Valid
    private CustomerRequest debtor;

委托金额如下:

    @Data
public class InstructedAmount {

    @NotBlank(message = "currency.required")
    private String currency;
    @NotBlank(message = "value.required")
    private String value;
}

基本上,当有效负载中提供了 instructedAmount 但例如我错过了有效负载中的货币属性时,验证工作正常,非空错误消息正确显示并且我的其余控制器端点未被调用。

然而,当有效负载中未提供 instructedAmount 时,不会显示任何强制性错误消息并调用我的其余端点,这是正确的方法还是我遗漏了什么?

我认为既然 InstructedAmount 的属性不能为空,那么 InstructedAmount 也不能​​为 null/empty。

如何在上面的注解场景中添加InstructedAmount not null验证?

@NotNull@Valid一起使用:

@NotNull
@Valid
private InstructedAmount instructedAmount;

来自https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-object-graph-validation

Note that null values are getting ignored during cascaded validation.