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

前端 未结 4 973
悲哀的现实
悲哀的现实 2020-12-03 03:16

I have a very simple Spring Boot application that uses Spring-Data-Mongodb

All I want to do is set a JSR-303 validation rule that says the object I\'m saving must ha

相关标签:
4条回答
  • 2020-12-03 03:48

    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.

    0 讨论(0)
  • 2020-12-03 03:51

    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.

    0 讨论(0)
  • 2020-12-03 03:56

    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.

    0 讨论(0)
  • 2020-12-03 04:03

    Starting with Spring Boot 2.3 the spring-boot-starter-validation dependency has to be added in pom.xml (for Maven):

    <dependency> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-validation</artifactId> 
    </dependency>
    

    Declaring a validator bean is not necessary.

    0 讨论(0)
提交回复
热议问题