我试图将@NotNull约束添加到我的Person对象中,但是我仍然可以@POST具有空电子邮件的新Person。我在MongoDB上使用Spring Boot Rest。
实体类:
import javax.validation.constraints.NotNull; public class Person { @Id private String id; private String username; private String password; @NotNull // <-- Not working private String email; // getters & setters }
存储库类:
@RepositoryRestResource(collectionResourceRel = "people", path = "people") public interface PersonRepository extends MongoRepository<Person, String> { }
应用类别:
@SpringBootApplication public class TalentPoolApplication { public static void main(String[] args) { SpringApplication.run(TalentPoolApplication.class, args); } }
pom.xml
... <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.BUILD-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ...
当我通过邮递员@POST一个新对象时,例如:
{ "username": "deadpool", "email": null }
我仍然STATUS 201使用此有效负载创建:
STATUS 201
{ "username": "deadpool", "password": null, "email": null .... .... }
我遇到了同样的问题,但是仅启用验证对我而言不起作用,这确实与JPA和MongoDb一起使用,以节省使用此方法的人。这不仅使验证有效,而且还得到了一个很好的宁静的400错误,而不是默认的500错误。
不得不将其添加到我的build.gradle依赖项中
compile('org.hibernate:hibernate-validator:4.2.0.Final')
和这个配置类
@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()); } }