【问题标题】:Can't read interpolated values in Java validation无法在 Java 验证中读取插值
【发布时间】:2019-03-01 13:36:47
【问题描述】:

在我的 Spring MVC 应用程序中,我使用 JSR-303 在我的控制器中使用 @Validated 对象。在我的 Spring 应用程序上下文中,我定义了一个自定义 MessageSource,用于从 resources/messages.properties 文件中读取消息。

我能够读取和覆盖 javax.validation 默认消息(例如 NotNull),但如果我尝试使用消息插值来读取参数(例如:来自@Size(max=...) 的最小值或最大值),则会出现错误。

请注意,如果我直接在模型中设置消息,它会正确显示“内插”消息(默认消息也可以正常工作)。

模型类:

    public class Customer {

            @JsonProperty("name")
            @NotNull
            @Size(max = 50) // if I add message = "This field must be less than {max} characters long" it works!
            private String name;

            // Other fields here + getters and setters
    }

messages.properties:

Size=This field must be less than {max} characters long
NotNull=This field must be set.

【问题讨论】:

    标签: java spring spring-boot spring-mvc javax.validation


    【解决方案1】:

    通过使用位置参数而不是命名参数解决了这个问题(不知道为什么它们不起作用)。

    Size=This field must be less than {1} characters long
    

    【讨论】:

      【解决方案2】:

      如果您想更好地控制消息,例如。不同的类有不同的消息,你可以试试这种方法

          @NotBlank(message = "{product.name.blank}")
          @Size(min = 2, message = "{product.name.minsize}")
          @ApiModelProperty(value = "Product Name", required = true, example = "Jabuke", position = 0)
          private String name;
      

      您将消息存储在 ValidationMessages.properties 而不是 application.properties。它会自动加载到上下文中。

      product.name.blank=Product name can not be blank
      product.name.minsize=Product name must be 2 characters or more
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 2018-07-12
        • 1970-01-01
        • 2019-01-30
        • 1970-01-01
        • 2021-07-07
        相关资源
        最近更新 更多