我正在尝试使用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!"}
答案 0 :(得分:0)
我没有配置WebDataBinder。
我的代码:
控制器就是这样
@PostMapping(value = "/url")
public Mono<Result> method(@RequestBody @Validated Message message) {
long time1 = System.currentTimeMillis();
//do sth
long time2 = System.currentTimeMillis();
return Mono.just(Result.withData(time2 - time1));
}
和Message类是这样的
@Getter
@Setter
public class Message implements Serializable {
private String content;
@Range(min = 1,max = 3)
private int length;
@NotNull
private String publisher;
}