Spring Validation vs Hibernate Validation

前端 未结 2 1412
我在风中等你
我在风中等你 2021-02-07 04:47

I am confused between the two now. I know Hibernate Validator 6 is the reference implementation for Bean Validation 2.0 specs. It supports Grouping, Internationalization of er

相关标签:
2条回答
  • 2021-02-07 05:28

    according to Spring Validation documentation

    With Bean Validation, a single javax.validation.Validator instance typically validates all model objects that declare validation constraints. To configure such a JSR-303 backed Validator with Spring MVC, simply add a Bean Validation provider, such as Hibernate Validator, to your classpath

    you can verify that by creating sample spring-boot project with spring-boot-starter-web dependency. It actually adds hibernate-validator dependency into your classpath

    Here are couple of links to jsr-303 in spring tutorials:

    1. https://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/

    2. https://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

    0 讨论(0)
  • 2021-02-07 05:47

    Hibernate Validation is implementation of JSR 303: Bean Validation API. Spring has its Validation package (it supports JSR 303: Bean Validation API but not proper implimentation).

    You could note that org.springframework.validation.Validator is different from javax.validation.Validator.

    You can perform Spring Validation just by creating a class implementing org.springframework.validation.Validator as simple as here But in case you need to follow the specifications of JSR 303: Bean Validation API you do it through Hibernate Validator.

    Okay to put in some more details.

    1) If you want to perform (some) validation, this can be done using spring. (below is some snippet):

    import org.springframework.validation.Validator;
    
    class MyService{
         Validator validator =  new MyValidator();
         //perform validation
        }
    class MyValidator implements Validator{
        // Your own validation logic. You may use ValidationUtils to help. 
    
    }
    

    2) If you want to perform (JSR 303 specification) validation you need to have its provider like Hibernate.

    import javax.validation.Validator;
    class MyService{
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); //Bootstraping
            Validator validator = factory.getValidator(); 
           //perform validation
    }
    

    The Bootstraping process above,is supported by Spring Framework. All you need to do is let spring create the bean for LocalValidatorFactoryBean

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

    and inject this bean.

    import javax.validation.Validator;
    
    @Service
    public class MyService {
    
        @Autowired
        private Validator validator;
    }
    
    0 讨论(0)
提交回复
热议问题