Manually call Spring Annotation Validation

后端 未结 6 1701
太阳男子
太阳男子 2020-11-29 02:42

I\'m doing a lot of our validation with Hibernate and Spring Annotations like so:

public class Account {
    @NotEmpty(groups = {Step1.class, Step2.class})
          


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:29

    Here is a code sample from JSR 303 spec

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    
    Driver driver = new Driver();
    driver.setAge(16);
    Car porsche = new Car();
    driver.setCar(porsche);
    
    
    Set> violations = validator.validate( driver );
    

    So yes, you can just get a validator instance from the validator factory and run the validation yourself, then check to see if there are violations or not. You can see in the javadoc for Validator that it will also accept an array of groups to validate against.

    Obviously this uses JSR-303 validation directly instead of going through Spring validation, but I believe spring validation annotations will use JSR-303 if it's found in the classpath

提交回复
热议问题