I have a problem with bean validation with hibernate-validator 4.x. Custom validator Interdate not called at all.
My over simplificated code is like hibernate doc http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-customconstraints.html
What is missing ?
pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.beginningee6.sample</groupId>
<artifactId>beanvalidation1</artifactId>
<packaging>jar</packaging>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
<build>
<finalName>validation-jpa1</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
All the java code :
import java.util.Set;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
public class M {
@Constraint(validatedBy = Interdate.class)
public @interface InterdateI {
String message() default "Boum";
String[] groups() default {};
}
class Interdate implements ConstraintValidator<InterdateI, Book> {
@Override
public void initialize(InterdateI constraintAnnotation) {
}
@Override
public boolean isValid(Book value, ConstraintValidatorContext context) {
return false;
}
}
public class Book {
@InterdateI
private String a;
}
public void i() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Book book = new Book();
Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book);
System.out.println(constraintViolations.size());
}
public static void main(String[] args) {
new M().i();
}
}
I suppose you shuold add these annotations to your constraint annotation:
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = Interdate.class)
@Documented
public @interface InterdateI {
String message() default "Boum";
String[] groups() default {};
}
otherwise without @Retention(RUNTIME) the annotion @InterdateI on Book.a field is not retained at runtime.
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.