How to obtain ConstraintValidatorContext?

前端 未结 3 783
予麋鹿
予麋鹿 2021-01-13 20:31

I am writing code that has explicit call to Bean Validation (JSR-303) something like this:

public class Example {

    @DecimalMin(value = \"0\")
    private         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 21:15

    The simple answer is you cannot. ConstraintValidatorContext is an interface and there is no Bean Validation API to get an instance like this. You could write your own implementation, but to implement it properly you would have to re-implement a lot of functionality of a Bean Validation provider. Look for example at the Hibernate Validator specific implementation - https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/internal/engine/constraintvalidation/ConstraintValidatorContextImpl.java

    That said, I believe your attempt of reuse is misguided. This is not in the indent of Bean Validation and you are ending up with non portable and hard to maintain code. If you want to reuse existing constraints have a look at constraint composition, for example @NotEmpty reusing @NotNull and @Size

    @Documented
    @Constraint(validatedBy = { })
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @ReportAsSingleViolation
    @NotNull
    @Size(min = 1)
    public @interface NotEmpty {
        String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";
    
        Class[] groups() default { };
    
        Class[] payload() default { };
    
        /**
         * Defines several {@code @NotEmpty} annotations on the same element.
         */
        @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
        @Retention(RUNTIME)
        @Documented
        public @interface List {
            NotEmpty[] value();
        }
    } 
    

提交回复
热议问题