greengrassbluesky greengrassbluesky - 2 months ago 18
reST (reStructuredText) Question

Spring 3 - Annotation based Bean Validation

I am building a REST API. Its made up of a Resource ( @Controller ) which returns a response 204 even when one of the mandatory field is not present.

I am using Spring 3.1, validation-api (1.1.0.Final) & Hibernate-validator(4.3.0). Not sure if Hibernate-validator plays any role here.

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
</exclusions>
</dependency>


I have a spring controller @Controller and a Bean with @Component

@POST
@Consumes(value = {MediaType.APPLICATION_JSON})
@Produces(value = {MediaType.APPLICATION_JSON})
@RequestMapping(method = RequestMethod.POST)
public Response addUserData(@Valid @RequestBody UserData userDataRequest) throws ResourceException {
...
}


My UserData bean has

@Component
public class UserData {

@NotNull(message = "user ID should not be null")
@Min(value = 1, message = "user ID should not be empty")
@Max(value = 20, message = "user ID should have length of more than 20")
@Pattern(regexp="[A-Z][a-z]+", message = "Only Alphanumeric characters allowed")
private String userId;

}


My validations are not getting executed. When I dont pass "userId", there is no error thrown. What am I missing here ?

Answer

I ultimately ended up using Jersey Bean Validation, instead of Spring. This is because rest of my code is using Jersey anyways. To make this work I just imported Jersey Bean Validation jar and added a small change to web.xml. Validations are now working.

Thank you @Manual Jordan. I will upvote your answer, since it gave me the right clues.

<!--  jersey beanValidation  -->
       <init-param>
           <param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
           <param-value>true</param-value>
       </init-param>