How to I get Spring-Data-MongoDB to validate my objects?

好久不见. 提交于 2019-11-27 14:02:21

First make sure that you have JSR-303 validator on classpath, for example:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.2.0.Final</version>
</dependency>

If you use Java config, the way to go is to create 2 beans:

@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
    return new ValidatingMongoEventListener(validator());
}

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

Voilà! Validation is working now.

Adding a Validator to the context is a good first step, but I don't think it will interact with anything unless you ask it to. The Spring Data guys can probably say for sure but I think you need to explicitly declare some listeners as well. There's an old blog on the feature, but you can find that by googling as easily as I can.

If you think there would be a useful autoconfig feature in Spring Boot, feel free to make a detailed proposal on github.

I found that if I add

public User addUser(@RequestBody  @Valid User newUser, 
                   BindingResult bindingResult) throws Exception {

  if (bindingResult.hasErrors()) {
    throw new Exception("Validation Error");
  }

To my controller this validates the incoming json against my rules, though I should still try and setup the validatingMongoEventListener to intercept any other parts of my code that attempt to update the model with invalid data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!