using validators in spring-data-rest returns http 500 instead of 400

夙愿已清 提交于 2019-12-03 06:00:38

Seem to have got it working; i had to override the validatingRepositoryEventListener() and manually add validators to the listener;

@Configuration
public class RestExporterRestConfig extends RepositoryRestMvcConfiguration {

    @Bean
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    @Override
    public ValidatingRepositoryEventListener validatingRepositoryEventListener() {
        ValidatingRepositoryEventListener listener = new ValidatingRepositoryEventListener();
        configureValidatingRepositoryEventListener(listener);
        listener.addValidator("afterCreate", validator());
        listener.addValidator("beforeCreate", validator());
        return listener;
    }

}

I now get a 400 returned as follows;

400 Bad Request
{"errors":
    [{  "entity":"Account",
        "message":"size must be between 0 and 10",
        "invalidValue":"login 0dsfdsfdsfdsfdsfdsfdsfds",
        "property":"login"
    }]
}

The previous answers didn't work for me, I think due to changes in Spring Data Rest so here is an updated answer that did work with JPA and MongoDb to save anyone else spending ages on this.

Had to add this to my build.gradle dependencies

    compile('org.hibernate:hibernate-validator:4.2.0.Final')

and this config class

@Configuration
public class CustomRepositoryRestConfigurerAdapter extends RepositoryRestConfigurerAdapter {


   @Bean
   public Validator validator() {
       return new LocalValidatorFactoryBean();
   }

   @Override
   public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
       validatingListener.addValidator("afterCreate", validator());
       validatingListener.addValidator("beforeCreate", validator());
       validatingListener.addValidator("afterSave", validator());
       validatingListener.addValidator("beforeSave", validator());
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!