How to I get Spring-Data-MongoDB to validate my objects?
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.
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.
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.
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.