我有一个notification.max-time-to-live
在application.yaml
文件中调用的变量,并希望将其用作javax.validation.constraints.@Max()
注释的值。
我已经尝试了很多方法(使用 env.getProperty()、@Value 等),它说它必须是一个常量值,有没有办法做到这一点?
我有一个notification.max-time-to-live
在application.yaml
文件中调用的变量,并希望将其用作javax.validation.constraints.@Max()
注释的值。
我已经尝试了很多方法(使用 env.getProperty()、@Value 等),它说它必须是一个常量值,有没有办法做到这一点?
我知道这并不能直接回答我的问题,正如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;
// ...
}