Spring Boot - обязательные поля класса @RequestBody - PullRequest
0 голосов
/ 06 мая 2020

У меня есть следующее определение API:

@ResponseBody
@PostMapping(path = "/configureSection")
public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
                                                       @RequestBody SectionConfig sectionConfig);
public class SegmentConfig {
    @JsonProperty(value = "txConfig", required = true)
    TelemetryConfig telemetryConfig;
    @JsonProperty(value = "rxConfig")
    ExternalConfig externalConfig;
}

Я определил, что txConfig является обязательным атрибутом (который является классом), но при отправке пустого JSON ({}) весенняя загрузка все еще выполняется API, хотя я ожидаю, что он вернет ошибку, когда параметр tsConfig не был установлен.

Есть идеи, что мне не хватает?

Изменить: использование @Valid и @NotNull решило это, но возвращенная ошибка слишком информативна, как ее исправить?

 {
    "timestamp": 1588753367913,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
    "errors": [
        {
            "codes": [
                "NotNull.segmentConfig.telemetryConfig",
                "NotNull.telemetryConfig",
                "NotNull.services.TelemetryConfig",
                "NotNull"
            ],
            "arguments": [
                {
                    "codes": [
                        "segmentConfig.telemetryConfig",
                        "telemetryConfig"
                    ],
                    "arguments": null,
                    "defaultMessage": "telemetryConfig",
                    "code": "telemetryConfig"
                }
            ],
            "defaultMessage": "Please provide a valid txConfig",
            "objectName": "segmentConfig",
            "field": "telemetryConfig",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Bad Request",
    "path": "/mypath"
}`

1 Ответ

1 голос
/ 06 мая 2020

Используйте аннотации @Valid и @NotNull для проверки, как показано ниже: -

@ResponseBody
    @PostMapping(path = "/configureSection")
    public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
                                                       @RequestBody @Valid SectionConfig sectionConfig
                                                        )  {

public class SegmentConfig {

    @JsonProperty(value="txConfig", required = true)
    @NotNull(message="Please provide a valid txConfig")
    TelemetryConfig telemetryConfig;
    @JsonProperty(value="rxConfig")
    ExternalConfig externalConfig;

}
...