繁体   English   中英

如何在 Spring Boot 中使用带参数的 ValidationMessages 属性文件?

[英]How to use ValidationMessages properties file with parameters in Spring Boot?

我正在使用 Spring 引导验证来验证某些字段。

我在资源下创建了ValidationMessages.properties文件,并覆盖了 Size 的默认验证值,如下所示:

javax.validation.constraints.Size.message=Please enter a value. Maximum length is {max}.

这就像一个魅力,在运行时{max}标记被替换为来自注释@Size(max = 100)的值。


现在我想定义一个自定义专有条目,例如:

my.custom.message=Hey, my custom value is {customValue}

问题是 - 如何在运行时从类似的东西开始替换{customValue}令牌?

private static final String CUSTOM_STRING = "{my.custom.message}";

在验证上下文中,您必须使用如下内容:

@Documented
@Constraint(validatedBy = MyValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{

    int customValue() default "THIS IS CUSTOM"; // this will be the value that will be injected in the custom message,
                                                // and can be changed when using the annotation

    String message() default "{my.custom.message}";

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

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

}

另外,如果您使用private static final String CUSTOM_STRING = "{my.custom.message}"; 在验证的上下文中,将完成替换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM