【发布时间】:2016-08-07 13:19:56
【问题描述】:
我正在尝试将 @NotNull 约束添加到我的 Person 对象中,但我仍然可以 @POST 带有空电子邮件的新 Person。我正在将 Spring Boot Rest 与 MongoDB 一起使用。
实体类:
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>
...
当我通过 Postman @POST 一个新对象时:
{
"username": "deadpool",
"email": null
}
我仍然得到使用此有效负载创建的STATUS 201:
{
"username": "deadpool",
"password": null,
"email": null
....
....
}
【问题讨论】:
-
好的,所以无论你收到什么参数,在对象前用
@Valid标记 -
@dambros 他的存储库有一个
@RepositoryRestResource注释,在这种情况下你不需要控制器。如果你使用它,Spring 会自动为 REST 调用创建一个控制器。 -
@oxyt,所以这仅适用于基于 JPA 的实现,因为在通过 JPA 插入/更新数据之前会进行有效性检查,并且它会干净地沸腾。我认为这对 Spring Data Hateoas 团队在 Web 级别提出了很好的功能要求。我认为您应该在他们的 github 位置打开一个,看看您是否收到有关此问题的更多反馈。
-
@oxyt,在这里打开了一个 github 问题 - github.com/spring-projects/spring-hateoas/issues/446
-
你必须启用validation。
标签: json spring mongodb rest spring-data-rest