Spring 具有可配置约束值的 Bean 验证

Spring Bean Validation with configurable constraint values

我想使 Java Bean 验证约束可由 Spring 配置,可能是通过使用属性。一个例子:

class Pizza {

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

}

我无法让它工作或找到很多关于它的文档。

这样的事情有可能吗?我知道消息在 Validationmessages.properties 文件中是可配置的,所以我希望约束值可以有类似的东西。

对于任何自定义验证,您需要通过实现 ConstraintValidator 接口来实现 自定义验证器 ,然后将该自定义验证器提供给您创建的自定义验证注释创建。

自定义验证器:

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;
    }

}

自定义验证注解:

@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 {};
}

使用自定义验证注释:

class Pizza {

    @MaxGramsOfCheese
    int gramsOfCheese;

}

请注意,如果您希望从属性文件访问注释的值,则必须在自定义验证器中提供该值,如图所示。

除了 @Madhu Bhat,您还可以配置您的 ConstraintValidator class 以从 Spring 的 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;
    }

}

因此,您可以在具有不同参数的不同字段上使用 @MaxGramsOfCheese 注释,这可能更适合您的情况。

class Pizza {

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

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

}