Bean验证2.0不适用于Map中的嵌套对象

问题描述 投票:1回答:1

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应该可以做到这一点。

你知道我做错了吗?我需要编写自定义验证器吗?

java spring-boot validation bean-validation
1个回答
0
投票

要使其正常工作,您必须执行以下操作:

MethodValidationPostProcessor bean添加到配置中

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
}

@Validated添加到您的EmployeeController

@Validated
@RestController
public class EmployeeController {}'

@Valid添加到MapEmployee

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();
    }

}

希望它对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.