【问题标题】:Spring Boot Hibernate Validator ExceptionSpring Boot Hibernate 验证器异常
【发布时间】:2018-08-27 16:58:04
【问题描述】:

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

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/" }

【问题讨论】:

    标签: hibernate spring-boot hibernate-validator


    【解决方案1】:

    声明这个 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。

    【讨论】:

    • 只有使用 validator.validate() 他会抛出异常还是我需要抛出?以及如何
    • valid 和 validate 注解会处理你的对象并为你抛出异常(ConstraintViolationException)。
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多