有时候参数校验的需求是只允许从指定的几个数据中选用一个,否则抛出异常。 如果是 数字类型可以通过自定义注解 + 校验规则。 使用示例:String
类型的可以用 @Pattern
注解写正则表达式,例如: @Pattern(regexp = "^(CENTURIES|YEARS|MONTHS|DAYS)$", message = "持续时间单位错误")
private String durationUnit;
OneOf.java
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = OneOfValidator.class)
@Documented
@Repeatable(List.class)
public @interface OneOf {
String message() default "Invalid parameter";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
// 用 double 接收可用值,兼容整数和小数
double[] value();
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Documented
@interface List {
OneOf[] value();
}
}
OneOfValidator.java
public class OneOfValidator implements ConstraintValidator<OneOf, Number> {
private Set<Double> allowedValues;
@Override
public void initialize(OneOf constraintAnnotation) {
allowedValues = Arrays.stream(constraintAnnotation.value()).boxed().collect(Collectors.toSet());
}
@Override
public boolean isValid(Number value, ConstraintValidatorContext constraintValidatorContext) {
return value == null || allowedValues.contains(value.doubleValue());
}
}
@OneOf(value = {128, 192, 320}, message = "比特率只能为 128, 192, 320")
private Integer bitRate;
· 转载请注明 https://kytrun.com/java-validation-one-of/