Spring Boot Hibernate Validator异常

时间:2018-08-27 16:58:04

标签: hibernate spring-boot hibernate-validator

我在保存之前使用休眠验证器来验证我的实体

Set<ConstraintViolation<Selo>> error = validator.validate(seloNovo);

所以。就像我在控制器中添加@Valid一样,是否有可能引发该错误?

类似这样的东西:

{
    "timestamp": "2018-08-27T16:57:16.386+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotEmpty.atoRtdpj.sgTabelaCustas",
                "NotEmpty.sgTabelaCustas",
                "NotEmpty.java.lang.String",
                "NotEmpty"
            ],
            "arguments": [
                {
                    "codes": [
                        "atoRtdpj.sgTabelaCustas",
                        "sgTabelaCustas"
                    ],
                    "arguments": null,
                    "defaultMessage": "sgTabelaCustas",
                    "code": "sgTabelaCustas"
                }
            ],
            "defaultMessage": "must not be empty",
            "objectName": "atoRtdpj",
            "field": "sgTabelaCustas",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotEmpty"
        }
    ],
    "message": "Validation failed for object='atoRtdpj'. Error count: 1",
    "path": "/selo/RTDPJ/" }

1 个答案:

答案 0 :(得分:0)

声明此bean。

@Bean(name = "messageSource")
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

@Bean(name = "validator")
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
    localValidatorFactoryBean.setValidationMessageSource(messageSource());
    return localValidatorFactoryBean;
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    MethodValidationPostProcessor validationPostProcessor = new MethodValidationPostProcessor();
    validationPostProcessor.setValidator(validator());
    return validationPostProcessor;
}

将消息保存在src / main / resources / messages中,并将其命名为:messages_en_US.properties。当然,您可以使用多种语言。

我的spring-boot版本是1.5.12.RELEASE。