控制器方法中的java@Valid和@RequestBody
我有一个奇怪的问题,我无法解决或找到答案
我定义了自己的验证器:
@Component
public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> {
@Autowired(required = true)
private UserService userService;
...
}
没有@Valid注释,我无法让注入工作,而是需要像这样注入
@Component
public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> {
@Autowired(required = true)
private UserService userService;
@Override
public void initialize(SingleInstanceRule singleInstanceRule) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
...
}
这使得它能够注入用户服务。然而,有了这个解决方案,我无法让@ExceptionHandler工作,注入也会在我们的测试中失败
使用@Valid,我可以使注入和@ExceptionHandler都正常工作(捕获BindException.class)
然而。。。这就是我不明白的问题。我不能将@RequestBody与@Valid一起使用,@Autowired此时不起作用,@ExceptionHandler也不起作用
所以在我们做这个之前:
@RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Plan create(@RequestBody final Plan entity) throws Exception {
...
}
现在我想要这个:
... (same annotations before)
public Plan create(@Valid @RequestBody final Plan entity) throws Exception {
...
}
但这将失败。我试过了,觉得这会管用的,果然管用了
... (same annotations before)
public Plan create(@Valid Plan entity) throws Exception {
...
}
但是我们需要@RequestBody注释,否则计划实体的一些关系就会丢失
有人知道我们如何使用@Valid和@RequestBody实现自动连接自定义验证器并使用@ExceptionHandler注释处理异常吗
共 (0) 个答案