Spring 请求正文的基于 MVC 的 Rest 服务验证

Spring MVC Based Rest Services Validations for request body

我的应用程序中有 Rest Controller,它具有如下代码片段:-

@RestController
@RequestMapping("/api/v1/user")
public class UserRestControllerV1 {

    @PostMapping("")
    public Response registerUser(@RequestBody @Valid final Request<UserDto> request,
                             final HttpServletRequest httpServletRequest,
                             BindingResult result){
    Response response = new Response(request);

    if(result.hasErrors()){
        response.setData(new String("Error"));
    }else {
        response.setData(new String("Test"));
    }
    return response;
}

请求Class:-

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
    @JsonProperty(value = "co-relation-id")
    private String coRelationID;

    @NotNull(message = "The request body should be present")
    private T data;

    /*
     ..... various other fields
     Getters / Setters
    */
}

UserDto Class :-

public class UserDto {

    @NotNull(message = "The username should not be null")
    private String username;

    @NotNull(message = "The password should not be null")
    @JsonIgnore
    private String password;

    /*
     ..... various other fields
     Getters / Setters
    */    
}

问题:我在此处进行验证时遇到问题。请求 class 中的字段 private T data 得到验证,但 T 中的字段 - 在 UserDto 的情况下未得到验证。

所以我需要知道实现此目的的方法或代码片段。

我已经尝试在配置中配置 hibernate validator bean,但在场景中没有帮助

@Valid 约束将指示 Bean 验证器深入研究其应用的类型 属性 并验证在那里找到的所有约束。

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
  @JsonProperty(value = "co-relation-id")
  private String coRelationID;

  //@NotNull(message = "The request body should be present")
  @Valid
  private T data;

  /*
   ..... various other fields
   Getters / Setters
  */
}