Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...