javahibernatetomcatbean-validation

How to use Bean Validation 2.0 (JSR 380) features in Tomcat 8?


Bean Validation 2.0 (JSR 380) should be able to perform the following validation:

@Valid
public class MyBean{
  private List<@NotNull String> members;
}

But it seems to just ignore the @NotNull annotation. Also, @NotBlank and @NotEmpty annotations are ignored.

I have the Bean Validation 2.0 API and reference implementation in my class path via Maven:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

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

I use Java 8 and Tomcat 8 with Jersey.

Do I need to configure Tomcat somehow to use the 2.0 implementation and not the default one that is bundled in JDK 8 (Like enabling Optional<> support in Jackson)?


Solution

  • The cause of the issue was that the Bean Validation extension for Jersey brings an older version of Hibernate validator implicitly, while the Hibernate validator I explicitly requested in the pom.xml is not used.

    To solve it, I excluded the hibernate validator that Jersey pulls implicitly:

    <dependency>
                <groupId>org.glassfish.jersey.ext</groupId>
                <artifactId>jersey-bean-validation</artifactId>
                <version>2.27</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-validator</artifactId>
                    </exclusion>
                </exclusions>
     </dependency>
    

    add my version of Bean Validation

         <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
    
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.15.Final</version>
        </dependency>
    

    and added Java EL:

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
            <version>3.0.1-b09</version>
        </dependency>
    
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>test</scope>
        </dependency>