我正在尝试为我的 Spring Boot Rest 服务设置一个自定义验证器和一个 ExceptionHandler,当我添加 ExceptionHandler 时,验证错误没有发送到 UI。所以我试图覆盖 handleMethodArgumentNotValid 方法,但这也不起作用。有人可以对此有所了解吗?
这就是我在控制器中配置验证类的方式 -
package services.rest.controller;
import java.io.IOException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
import services.rest.model.TestInput;
import services.rest.validator.DataValidator;
@RestController
@RequestMapping("/test")
@Slf4j
public class RestResource {
@Autowired
private DataValidator validator;
@PostMapping("/create")
public String create(@Valid final TestInput input) throws IOException {
log.debug(input.toString());
return "Success";
}
@InitBinder()
public void init(final WebDataBinder binder) {
binder.addValidators(validator);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 ExceptionHandler 代码 -
package services.rest.exceptionhandler;
import java.util.ArrayList; …Run Code Online (Sandbox Code Playgroud)