简体   繁体   中英

SpringBoot Bean validation @NotEmpy is not Working

I been trying to use spring @NotEmpty to make some input paramters in a REST api mandatory.

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.

Im using spring boot 2.2.2.RELEASE, is there some know bug or issue about this?

I've had exactly the same issue and the solution that worked for me was to explicitly require a newer hibernate-validator version.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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