springboot hibernate @Valid不生效以及javax.validation.ValidationException: HV000032问题处理

在java项目中写bean校验的时候太麻烦就用hibernate-validator来校验,遇到了两个问题记录一下

@Valid不生效

在springboot中配置Validator

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class ValidatorConfiguration {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}

一个报错 javax.validation.ValidationException: HV000032: Unable to initialize org.hibernate.validator.internal.constraintvalidators.bv.size.SizeValidatorForCharSequence.

导致这个问题有很多原因,一个是没有引入javax.el-api,另一个是属性配置问题引起的

最终pom中关于hibernate校验的依赖,请检测是否都引入了

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.13.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>

一个错误的属性配置

@Size(min = 10, max = 6, message = "验证码长度应该在4-6位之间")

如果min比max大就会引起

javax.validation.ValidationException: HV000032: Unable to initialize org.hibernate.validator.internal.constraintvalidators.bv.size.SizeValidatorForCharSequence.

一个测试示例

    @Size(min = 4, max = 6, message = "验证码长度应该在4-6位之间")
    @NotNull(message = "验证码不能为空")
    private String validateCode;

    @Max(value = 100, message = "数字最大值为20")
    @Min(value = 20, message = "数字最小值为20")
    @NotNull(message = "数字不能为空")
    private Long number;

改完pom记得在pom文件上右键Maven->Reimport

相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页