As your error message suggests, you cannot have expressions in annotation values and therefore you'll need to use a custom validation annotation.
It's relatively easy to do this:
Annotation
@Constraint(validatedBy = AgeConstraintValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface MaxAge {
/**
* The age against which to validate.
*/
int value();
String message() default "com.mycompany.validation.MaxAge.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Constraint Validator
public class AgeConstraintValidator implements ConstraintValidator<MaxAge, Integer> {
private int maximumAge;
@Override
public void initialize(MaxAge constraintAnnotation) {
this.maximumAge = constraintAnnotation.value();
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return value.intValue() <= this.maximumAge;
}
}
Then you can just annotate your field with @MaxAge(50)
and it should work.