2012-02-08 14 views
0

hibernate-validator 4.xでBeanの検証に問題があります。カスタムバリデータInterdateはまったく呼び出されません。Java Beanの検証、hibernate-validator 4.xおよびConstraintValidatorの問題

マイオーバーsimplificatedコードが欠けている何休止ドキュメント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(); 
} 
    } 

答えて

0

私はあなたがあなたの制約注釈にこれらの注釈を追加shuoldとします

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

    String[] groups() default {}; 
} 

それ以外の場合はut @ Retention(RUNTIME)annotion @InterdateI on Book.aフィールドは実行時に保持されません。

関連する問題