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