JSR303 Composite Annotation

♀尐吖头ヾ 提交于 2019-11-30 17:53:39

问题


I've created a composite annotation that consists of @Digits and @Min

@Digits(integer=12, fraction=0)
@Min(value=0)
@ReportAsSingleViolation
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target( { FIELD, METHOD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Constraint(validatedBy={})
public @interface PositiveInt {
     String message() default "{positive.int.msg}";
     Class<?>[] groups() default {};
     Class<? extends Payload>[] payload() default {};
}

my problem is, I want to reuse this annotation where I want the @Digits 'integer' value to be specify when the PositiveInteger is use

example

public Demo{
    @PositiveInteger(integer=1)
    private Integer num1;

    @PositiveInteger(integer=2)
    private Integer num2;
}

where num1 can be 1-9, and num2 can be 1-99.

Is this even possible, if so, how do I go about this?

Currently, I have to provides a custom ConstraintValidator where i would have my validation code for the @Digits and @Min

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target( { FIELD, ANNOTATION_TYPE, PARAMETER })
@Constraint(validatedBy=PositiveIntConstraintValidator.class)
public @interface PositiveInt {
         String message() default "positive.int.msg";
     Class<?>[] groups() default {};
     Class<? extends Payload>[] payload() default {};

     int integer() default 1;
}


public class PositiveIntConstraintValidator implements ConstraintValidator<PositiveInt, Number> {
    private int maxDigits;

    @Override
    public void initialize(PositiveInt constraintAnnotation) {
    maxDigits = constraintAnnotation.integer();

    if (maxDigits < 1){
        throw new IllegalArgumentException("Invalid max size.  Max size must be a positive integer greater than 1");
    }
}


@Override
public boolean isValid(Number value, ConstraintValidatorContext context) {
    if (value == null){
        return true;
    }
    else if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof BigInteger){
        String regex = "\\d{"0," + maxDigits + "}";
        return Pattern.matches(regex, value.toString());
    }
    return false;
}

回答1:


You could make use of @OverridesAnnotation:

@Digits(integer=0, fraction=0)
@Min(value=0)
@ReportAsSingleViolation
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target( { FIELD, METHOD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Constraint(validatedBy={})
public @interface PositiveInteger {
    String message() default "{positive.int.msg}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    @OverridesAttribute(constraint=Digits.class, name="integer")
    int digits();
}

That way the value given in @PositiveInteger#digits() will be propagated to @Digits.



来源:https://stackoverflow.com/questions/13844161/jsr303-composite-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!