Spring Data Rest Validation Confusion

后端 未结 3 1065
情书的邮戳
情书的邮戳 2020-12-13 16:40

Looking for some help with Spring data rest validation regarding proper handling of validation errors:

I\'m so confused with the docs regarding spring-data-rest vali

3条回答
  •  忘掉有多难
    2020-12-13 17:10


    @Mathias it seems the following is enough for jsr 303 annotations to be checked and for it to auto return a http code of 400 with nice messages (I dont even need BeforeCreateCompanyValidator or BeforeSaveCompanyValidator classes):

    @Configuration
    public class RestValidationConfiguration extends RepositoryRestConfigurerAdapter{
    
    @Bean
    @Primary
    /**
     * Create a validator to use in bean validation - primary to be able to autowire without qualifier
     */
    Validator validator() {
        return new LocalValidatorFactoryBean();
    }
    
    
    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        Validator validator = validator();
        //bean validation always before save and create
        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);
    }
    

    }

    400 response:

    {
        "errors": [{
            "entity": "Company",
            "message": "may not be null",
            "invalidValue": "null",
            "property": "name"
        }, {
            "entity": "Company",
            "message": "may not be null",
            "invalidValue": "null",
            "property": "address"
        }]
    }
    

提交回复
热议问题