【发布时间】:2018-02-05 07:34:53
【问题描述】:
我正在尝试在 Spring WebFlux 中使用 org.springframework.validation.Validator 验证 JSON @RequestBody,但我收到“内部服务器错误”并显示以下消息。
java.lang.IllegalStateException: Failed to resolve argument 1 of type 'org.springframework.validation.BindingResult' on public reactor.core.publisher.Mono ....
验证器类:
@Component
public class GreetingValidator implements Validator {
@Override
public boolean supports(Class<?> type) {
return GreetingSchema.class.equals(type);
}
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "content", "content.empty", "Content is required");
GreetingSchema greeting = (GreetingSchema) obj;
}
}
REST 控制器类:
@RestController
@RequestMapping("/greeting")
public class GreetingController {
@Autowired
private GreetingValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@GetMapping
public GreetingSchema get() {
return new GreetingSchema("Hello, World!");
}
@PostMapping(consumes = "application/json")
public Mono post(@Validated @RequestBody GreetingSchema body, BindingResult result) {
if (result.hasErrors()) {
return Mono.just(result.getFieldErrors());
}
return Mono.just("valid");
}
}
当我从 post 方法中删除 @RequestBody 注释后尝试如下
public Mono post(@Validated GreetingSchema body, BindingResult result)
然后它在没有“内部服务器错误”的情况下运行,但无法验证 JSON @RequestBody。
{"content": "Hello, Xyz!"}
【问题讨论】:
-
我使用的是spring-boot RC1。
标签: json spring validation spring-webflux spring-validator