简体   繁体   English

SpringBoot Bean 验证 @NotEmpy 不起作用

[英]SpringBoot Bean validation @NotEmpy is not Working

I been trying to use spring @NotEmpty to make some input paramters in a REST api mandatory.我一直在尝试使用 spring @NotEmpty在 REST api 中强制设置一些输入参数。

So far this is what I've achieved.到目前为止,这就是我所取得的成就。

RestController休息控制器

@RestController
public class ResourceController {

    @Autowired
    private GestionaDatosCrmService service;

    @PostMapping(path = Constantes.OBTENER_DATOS_CRM)
    @ResponseStatus(HttpStatus.CREATED)
    public ObtenerDatosCrmResponse obtenerDatosCrm(@RequestHeader HttpHeaders headerRequest,
            @Valid @RequestBody ObtenerDatosCrmRequest request, HttpServletResponse headerResponse) {
        return service.obtenerDatosCrm(headerRequest, request, headerResponse);
    }
}

Request Object请求对象

import javax.validation.constraints.NotEmpty;

//import org.hibernate.validator.constraints.NotEmpty;

public class ObtenerDatosCrmRequest {

    @NotEmpty(message = "Please provide a number")
    private String numSN;
    private String callID;

    public String getNumSN() {
        return numSN;
    }

    public void setNumSN(String numSN) {
        this.numSN = numSN;
    }

    public String getCallID() {
        return callID;
    }

    public void setCallID(String callID) {
        this.callID = callID;
    }
}

Note this important detail I'm using javax.validation.constraints.NotEmpty for the @NotEmpty annotation but that doesn't work when I change to org.hibernate.validator.constraints.NotEmpty that is Deprecated the @NotEmpty kicks in and I get a 400 Bad request error when testing.请注意这个重要的细节,我将javax.validation.constraints.NotEmpty用于@NotEmpty注释,但是当我更改为org.hibernate.validator.constraints.NotEmpty@NotEmpty已弃用,我得到测试时出现 400 Bad request 错误。

Im using spring boot 2.2.2.RELEASE, is there some know bug or issue about this?我正在使用 spring boot 2.2.2.RELEASE,是否有一些已知的错误或问题?

I've had exactly the same issue and the solution that worked for me was to explicitly require a newer hibernate-validator version.我遇到了完全相同的问题,对我有用的解决方案是明确要求更新的hibernate-validator版本。

Gradle:摇篮:

implementation 'org.hibernate.validator:hibernate-validator:6.1.2.Final'

Maven:马文:

<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.1.2.Final</version>
</dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM