![](/img/trans.png)
[英]How to override @annotations (javax.validation) in a subClass
[英]How to use application.properties values in javax.validation annotations
我在application.yaml
文件中有一個名為notification.max-time-to-live
的變量,我想將其用作javax.validation.constraints.@Max()
注釋的值。
我嘗試了很多方法(使用 env.getProperty()、@Value 等),它說它必須是一個常量值,有什么辦法可以做到這一點嗎?
我知道這並沒有直接回答我的問題,正如M. Deinum已經說過的那樣,答案是否定的。 N.netheless 這是一個簡單的解決方法。
@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();
}
}
現在我們只需要在相應的 class 中添加這個自定義注釋即可。
public class Notification {
private String id;
@ValidTimeToLive
private Integer timeToLive;
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.