如何使用messageSource bean处理Hibernate验证消息?

时间:2015-10-05 09:33:51

标签: spring hibernate validation

我有这个消息源 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?

2 个答案:

答案 0 :(得分:0)

你确定这不起作用(注释行)吗?将消息放在属性文件(resources / locale / message.properties)中应该有效...

答案 1 :(得分:0)

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

ErrorType.className.fieldName = message。

示例:

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 =网站地址错误。