Spring Validation vs Hibernate Validation

前端 未结 2 1413
我在风中等你
我在风中等你 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: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

    
    

    and inject this bean.

    import javax.validation.Validator;
    
    @Service
    public class MyService {
    
        @Autowired
        private Validator validator;
    }
    

提交回复
热议问题