Search code examples
javaspringbean-validation

Spring Bean Validation with configurable constraint values


I'd like to make Java Bean Validation constraints configurable by Spring, possibly by using properties. An example:

class Pizza {

    @MaxGramsOfCheese(max = "${application.pizza.cheese.max-grams}")
    int gramsOfCheese;

}

I haven't been able to get this to work or find much documentation about this.

Is something like this even possible? I know that messages are configurable in a Validationmessages.properties file, so I'm hoping something similar is possible for constraint values.


Solution

  • In addition to @Madhu Bhat you can configure your ConstraintValidator class to read properties from Spring's Environment.

    public class MaxGramsOfCheeseValidator implements ConstraintValidator<MaxGramsOfCheese, Integer> {
    
        @Autowired
        private Environment env;
    
        private int max;
    
        public void initialize(MaxGramsOfCheese constraintAnnotation) {
            this.max = Integer.valueOf(env.resolvePlaceholders(constraintAnnotation.max()));
        }
    
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            return value != null && value <= this.max;
        }
    
    }
    

    Thus you can use @MaxGramsOfCheese annotation on different fields with different parameters which may be more appropriate in your case.

    class Pizza {
    
        @MaxGramsOfCheese(max = "${application.pizza.cheddar.max-grams}")
        int gramsOfCheddar;
    
        @MaxGramsOfCheese(max = "${application.pizza.mozerella.max-grams}")
        int gramsOfMozerella;
    
    }