Spring-Boot How to properly inject javax.validation.Validator

后端 未结 1 1660
孤街浪徒
孤街浪徒 2020-12-04 19:24

I\'ve got a problem injecting the Validator into the spring application bean when attempting to validate a model using JSR-303 (hibernate-validator)

My

相关标签:
1条回答
  • 2020-12-04 19:46

    You need to declare a bean of type LocalValidatorFactoryBean like this:

    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    

    in XML or

    @Bean
    public javax.validation.Validator localValidatorFactoryBean() {
       return new LocalValidatorFactoryBean();
    }
    

    in Java Config.

    Edit:

    It is important to understand that if JPA is being used and is backed by Hibernate, then Hibernate will try to automatically validate your Beans as well as the Spring Framework. This can lead to the problem of javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator because Hibernate doesn't know about the Spring Context and as far as I can tell there is no way to tell it, not even with the LocalValidatorFactoryBean. This causes the Validator's to run twice. One correctly, and once that fails.

    In order to disable the default Hibernate ORM validation, the following property for Spring needs to be set:

    spring.jpa.properties.javax.persistence.validation.mode=none

    I updated this example, because it was the one I kept finding over and over again about the Validator's not being injected, and it turns out this was the problem I faced.

    This part of the Spring documentation has all the details

    0 讨论(0)
提交回复
热议问题