For any custom validation, you need to implement a custom validator by implementing the ConstraintValidator
interface, and then provide that custom validator to the custom validation annotation that you create.
The custom validator:
public class MaxGramsOfCheeseValidator implements ConstraintValidator<MaxGramsOfCheese, Integer> {
@Value("${application.pizza.cheese.max-grams}")
protected int maxValue;
@Override
public void initialize(MaxGramsOfCheese constraintAnnotation) {
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return value != null && value <= maxValue;
}
}
The custom validation annotation:
@Documented
@Constraint(validatedBy = {MaxGramsOfCheeseValidator.class})
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MaxGramsOfCheese {
String message() default "Some issue here"; //message to be returned on validation failure
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Using the custom validation annotation:
class Pizza {
@MaxGramsOfCheese
int gramsOfCheese;
}
Note that if you want the value for the annotation to be accessed from the properties file, you'll have to provide that in the custom validator as shown.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…