这是上一个问题Spring validator class is ignored by controller的衍生产品。我正在努力使我的控制器接受一个MultipartFile
对象,并使Spring将Validator
绑定到该对象。简而言之,这不有效:
@RequestMapping("/api")
@RestController
public class Controller{
private FileValidator fileValidator;
@Autowired
public myObjectController(FileValidator fileValidator){
this.fileValidator = fileValidator;
}
@InitBinder("file")
public void initFileBinder(WebDataBinder binder) {
binder.setValidator(this.fileValidator);
}
@PostMapping("myObject")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public MyObject createMyObject(
@RequestPart("file") @Valid MultipartFile file
){
return null; //201 CREATED every time
}
}
public class FileValidator implements Validator{
public boolean supports(Class<?> aClass) {
//Breakpoint on line below is never triggered.
return MultipartFile.class.isAssignableFrom(aClass);
}
public void validate(Object o, Errors e) {
//validation happening here
}
}
我不是互联网上第一个遇到类似问题的人。
https://stackoverflow.com/a/7256042/4640960
https://memorynotfound.com/spring-mvc-file-upload-example-validator/
https://stackoverflow.com/a/13085988/4640960
https://hackinghorse.blogspot.com/2016/08/devnote-uploading-multipart-file-with.html
所有示例都解决了我的问题,我将MultipartFile
包装在一个非常笨拙的包装器类中,以便@Valid
注释起作用。似乎这是必需的,但是为什么这是必需的?我必须强调,这个特定问题不是要解决我的技术问题,而是要了解使MultipartFile
注释忽略这些对象的问题@Valid
。