【问题标题】:How to use messageSource bean for processing Hibernate validation messages?如何使用 messageSource bean 处理 Hibernate 验证消息?
【发布时间】:2016-01-01 21:57:38
【问题描述】:

我有这个消息来源 bean。它适用于获取消息,例如来自org.springframework.validation.Validator

@Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource messageSource() {

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setCacheSeconds(-1);
    messageSource.setFallbackToSystemLocale(false);
    messageSource.setDefaultEncoding("UTF-8");
    messageSource.setBasename("classpath:/locale/messages");

    return messageSource;
}

我想使用这个 bean 来处理此类 POJO 类的 JSR 349 验证消息:

public class AuthorizationRequest {

    @NotEmpty
    //@NotEmpty(message = "validation.notEmpty")
    @JsonProperty("response_type")
    private String responseType;

    @NotEmpty
    //@NotEmpty(message = "validation.notEmpty")
    @JsonProperty("client_id")
    private String clientId;

    @NotEmpty
    //@NotEmpty(message = "validation.notEmpty")
    @JsonProperty("redirect_uri")
    private String redirectUri;

    private String scope;
// the rest omitted
}

但是来自的错误消息仍然是(本地化的)原始 Hibernate,例如 {org.hibernate.validator.constraints.NotEmpty.message}。但我想使用我自己的错误信息。我尝试了很多选项,但没有一个有效。

我想为整个应用程序保留一个消息属性文件。

问题

有什么方法可以告诉 Spring 使用我的 messageSource bean?

【问题讨论】:

    标签: spring hibernate validation


    【解决方案1】:

    您需要在资源包文件中遵循此格式。

    ErrorType.className.fieldName = 消息。

    示例:

    public class Call{
    @Pattern(regexp = "^(http://|https://)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?$")
    private String site;
    }
    

    然后像这样在资源包中定义消息

    Pattern.call.site = 站点地址错误。

    【讨论】:

      【解决方案2】:

      您确定这不起作用(注释行)?将您的消息放在属性文件 (resources/locale/message.properties) 中应该可以工作...

      【讨论】:

      • 它有效,但我想避免手动为所有约束定义消息键。
      • 哦,我误解了这个问题。在 /src/main/resources 下创建 ValidationMessages.properties 并覆盖您想要供自己使用的消息,例如“org.hibernate.validator.constraints.NotEmpty.message = your message for not empy”。
      猜你喜欢
      • 2016-10-09
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 2018-09-05
      • 2012-03-06
      • 2011-03-30
      • 2011-12-24
      相关资源
      最近更新 更多