虽然这个问题已经得到解答,但我很感兴趣为什么 @Validated
需要 Map<String, @Valid Employee>
的工作级联验证.
更新 2:为了更深入地了解,我找到了这些帖子( One 、 Two 和 Three ),其中解释了 @Validated
需要激活方法级验证。在此帮助下,可以验证集合,因为它们不是要验证的 JavaBean(JSR 303)。
解决方案:我已使用工作代码示例更新了我的代码片段和存储库。我所要做的就是用 @Validated
注释我的 Controller 并在Employee
中添加一些 setter/getter 。 MethodValidationPostProcessor
根本没有必要。
更新:我更新了我的问题并 fork 了 Spring Boot Rest 示例,以添加一个最小的 Rest API 来演示:
Github Repo 。 示例值位于 README.md 中!
<小时/>我有一个 Spring Boot 2 API 来存储一些员工。我可以通过任一 Employee
或 Map<String, Employee>
.
@Validated //this is the solution to activate map validation
@RestController
class EmployeeController {
@PostMapping("/employees")
List<Employee> newEmployee(@RequestBody @Valid Employee newEmployee) {
...
}
@PostMapping("/employees/bulk")
List<Employee> newEmployee(@RequestBody Map<String, @Valid Employee>
newEmployees) {
...
}
}
Employee 存在一些内部静态类,也需要验证:
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;
}
// getters
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;
}
// getters
}
}
目前,单个请求的验证有效,但批量请求的验证无效。据我所知,Bean 验证 2.0 应该可以实现这一点。
你知道我做错了什么吗?我需要编写自定义 validator 吗?
最佳答案
要使其正常工作,您必须执行以下操作:
Add
MethodValidationPostProcessor
bean to configuration
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
Add
@Validated
to yourEmployeeController
@Validated
@RestController
public class EmployeeController {}'
Add
@Valid
toMap
or toEmployee
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();
}
}
希望对您有帮助。
关于java - 级联 bean 验证 2.0 不适用于 Map 内的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167961/