自定义JPA Bean验证器,其参数与@Size类似

时间:2017-03-18 14:13:02

标签: java hibernate bean-validation

我希望为类似于@Size注释的注释实现JPA Bean验证器,因此允许在注释上使用参数minmax。我一直在查看文档和各种示例,但无法找到允许在Annotation上使用多个参数的实现。

目前我的代码看起来像这样

@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CapacityImpl.class)
public @interface Capacity {

    String message() default "Capacity not in valid Range";

    // Required by validation runtime
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

}

最终的注释应该如下@Capacity(min=19, max=40)

public class CapacityImpl implements ConstraintValidator<Capacity, Integer> {
    @Override
    public void initialize(Capacity capacity) {

    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        return false;
    }
}

所以我的问题是如何更改此接口和类以实际允许Annotation上的参数min和max,以便我可以使用这些参数值验证字段的值

2 个答案:

答案 0 :(得分:2)

只需将它们添加到注释定义中:

public @interface Capacity {

    String message() default "Capacity not in valid Range";

    // Required by validation runtime
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    int min();
    int max();
}

答案 1 :(得分:0)

public @interface Capacity {

    String message() default "Capacity not in valid Range";

    // Required by validation runtime
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    int min();
    int max();
}

验证器类

@Component
public class CapacityValidator implements ConstraintValidator<Capacity, String> {
    private  int min;
    private  int max;

    @Override
    public void initialize(Capacity constraintAnnotation){
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }
    @Override
    public boolean isValid(String capacity, ConstraintValidatorContext constraintValidatorContext) {
        //validate logic here e.g
       if(capacity > this.min){
         return true;
        }
    }
}