I just can't get validations to work. I have this simple endpoint that is part of an Spring Boot application:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(@Valid UserDTO userDTO, @Context UriInfo uriInfo) {
User user = UserParser.parse(userDTO);
userService.save(user);
final URI uri = uriInfo.getAbsolutePathBuilder().path(String.valueOf(user.getId())).build();
return Response.created(uri).build();
}
Then, the UserDTO to validate:
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserDTO {
private Long id;
// redundant validations, for testing
@NotNull
@Size(min = 5, max = 80, message = "First name too short")
@NotBlank(message = "First name blank")
@NotEmpty(message = "First name empty")
private String firstName;
@NotNull
@Size(min = 2, max = 80, message = "Last name too short")
private String lastName;
@NotNull
private String email;
}
And it always processes any request, even with empty fields. I even created a test endpoint to see if the problem was having the validations inside the DTO
@Path("/validator/{testInt}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String validator(@Valid @Min(value = 30, message = "testInt too small") @PathParam("testInt") Integer testInt) {
return String.valueOf(testInt);
}
But that doesn't work either, it happily returns any int it receives. In case it matters, my endpoint is a @Service
, and here is the relevant parts of my maven dependency tree:
[INFO] +- org.glassfish.jersey.ext:jersey-bean-validation:jar:2.22.1:compile
[INFO] | +- org.glassfish.hk2.external:javax.inject:jar:2.4.0-b31:compile
[INFO] | +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] | +- org.hibernate:hibernate-validator:jar:5.2.2.Final:compile
[INFO] | | +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] | | \- com.fasterxml:classmate:jar:1.1.0:compile
[INFO] | +- javax.el:javax.el-api:jar:2.2.4:compile
[INFO] | \- org.glassfish.web:javax.el:jar:2.2.4:compile
I also set breakpoints inside HibernateValidator
, and saw that two of its methods get called, so looks like it's running. Just not validating.
EDIT: My jersey configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(RequestContextFilter.class);
register(LoggingFilter.class);
register(JacksonFeature.class);
packages("com");
}
}
ValidationFeature
with Jersey. If it is already working, and it is just not the response you are expecting, the reporting behavior needs to be configured. Set the propertyServerProperties.BV_SEND_ERROR_IN_RESPONSE
to true in Jersey. Other than that I can't reproduce the behavior of it simply just not working, with what you've provided.