Update:我已经更新了我的问题,并派生了Spring Boot Rest示例,以添加一个最小的Rest API来演示:
Github Repo。示例值在README.md中!
我有一个Spring Boot 2 API来存储一些员工。我可以传递一个Employee
或一个Map<String, Employee>
。
@PostMapping("/employees")
List<Employee> newEmployee(@RequestBody @Valid Employee newEmployee) {
...
}
@PostMapping("/employees/bulk")
List<Employee> newEmployee(@RequestBody Map<String, @Valid Employee> newEmployees) {
...
}
员工存在一些内部静态类,这些类也需要验证:
public class Employee {
@NotBlank
public final String name;
@Valid
public final EmployeeRole role;
@JsonCreator
public Employee(@JsonProperty("name") String name,
@JsonProperty("role") EmployeeRole role) {
this.name = name;
this.role = role;
}
public static class EmployeeRole {
@NotBlank
public String rolename;
@Min(0)
public int rating;
@JsonCreator
public EmployeeRole(@JsonProperty("rolename") String rolename,
@JsonProperty("rating") int rating) {
this.rolename = rolename;
this.rating = rating;
}
}
}
目前,对单个请求的验证有效,但对我的批量请求无效。据我所知,使用Bean验证2.0应该可以做到这一点。
你知道我做错了吗?我需要编写自定义验证器吗?
要使其正常工作,您必须执行以下操作:
将
MethodValidationPostProcessor
bean添加到配置中
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
将
@Validated
添加到您的EmployeeController
@Validated
@RestController
public class EmployeeController {}'
将
@Valid
添加到Map
或Employee
public List<Employee> newEmployee(@RequestBody @Valid Map<String, Employee> newEmployees) {}
public List<Employee> newEmployee(@RequestBody Map<String, @Valid Employee> newEmployees) {}
就这些。这是整个EmployeeController
:
@Validated
@RestController
public class EmployeeController {
@PostMapping("/employees")
public List<Employee> newEmployee(@RequestBody @Valid Employee newEmployee) {
return Collections.singletonList(newEmployee);
}
@PostMapping("/employees/bulk")
public List<Employee> newEmployee(@RequestBody @Valid Map<String, Employee> newEmployees) {
return new ArrayList<>(newEmployees.values());
}
}
和SpringBoot配置文件
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
希望它对您有帮助。