JSR303复合注释

时间:2012-12-12 16:27:59

标签: java bean-validation

我创建了一个由@Digits和@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 {};
}

我的问题是,我想重用这个注释,我希望在使用PositiveInteger时指定@Digits'整数'值

例如

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

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

其中num1可以是1-9,num2可以是1-99。

这是否可能,如果是这样,我该怎么做呢?

目前,我必须提供一个自定义的ConstraintValidator,我将获得@Digits和@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 个答案:

答案 0 :(得分:14)

您可以使用@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();
}

这样,@PositiveInteger#digits()中给出的值将传播到@Digits