Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...