Java bean验证,hibernate-validator 4.x和ConstraintValidator的问题

时间:2012-02-08 13:32:34

标签: java hibernate bean-validation

我在使用hibernate-validator 4.x验证bean时遇到问题。根本没有调用自定义验证器Interdate。

我过度简化的代码就像hibernate doc http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-customconstraints.html

缺少什么?

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>

所有java代码:

    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();
}
    }

1 个答案:

答案 0 :(得分:0)

我想你应该将这些注释添加到约束注释中:

 @Target( { METHOD, FIELD, ANNOTATION_TYPE })
 @Retention(RUNTIME)
 @Constraint(validatedBy = Interdate.class)
 @Documented
 public @interface InterdateI {
   String message() default "Boum";

   String[] groups() default {};
 }

否则没有@Retention(RUNTIME),Book.a字段上的注释@InterdateI不会在运行时保留。