【问题标题】:How to use application.properties values in javax.validation annotations如何在 javax.validation 注释中使用 application.properties 值
【发布时间】:2021-09-27 17:31:32
【问题描述】:

我在application.yaml 文件中有一个名为notification.max-time-to-live 的变量,并希望将其用作javax.validation.constraints.@Max() 注释的值。

我尝试了很多方法(使用 env.getProperty()、@Value 等),它说它必须是一个常量值,有什么办法吗?

【问题讨论】:

  • 没有。这些注释由 javax.validation 而不是 Spring 处理。所以不,这是不可能的。您可以编写自己的验证器来读取此值并进行相应的验证。
  • 致选民:这个问题的答案是否定的,但问题作为一个问题是合理的。

标签: java spring spring-boot application.properties javax.validation


【解决方案1】:

我知道这不能直接回答我的问题,正如M. Deinum 已经说过的答案是。尽管如此,这是一个简单的解决方法。

@Max 和其他 javax 注释确实不允许我们使用动态值,但是,我们可以创建一个自定义注释(如 M. Deinum 建议的那样),它使用来自 application.yaml 的值和 spring @Value

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = ValidTimeToLiveValidator.class)
public @interface ValidTimeToLive {

    String message() default "must be less than or equal to %s";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

以及相应的验证器。

public class ValidTimeToLiveValidator implements ConstraintValidator<ValidTimeToLive, Integer> {

    @Value("${notification.max-time-to-live}")
    private int maxTimeToLive;

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        // leave null-checking to @NotNull
        if (value == null) {
            return true;
        }
        formatMessage(context);
        return value <= maxTimeToLive;
    }

    private void formatMessage(ConstraintValidatorContext context) {
        String msg = context.getDefaultConstraintMessageTemplate();
        String formattedMsg = String.format(msg, this.maxTimeToLive);
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(formattedMsg)
               .addConstraintViolation();
    }
}

现在我们只需要在相应的类中添加这个自定义注解。

public class Notification {

    private String id;
 
    @ValidTimeToLive
    private Integer timeToLive;

    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2019-06-25
    • 2022-12-22
    • 2020-11-16
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多