为什么在Spring的MultipartFile对象上忽略@Valid注释?

时间:2018-07-17 14:17:27

标签: java spring spring-boot wrapper spring-validator

这是上一个问题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
    }
}

我不是互联网上第一个遇到类似问题的人。

http://javabycode.com/spring-framework-tutorial/spring-mvc-tutorial/spring-mvc-file-upload-validation-example.html

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

0 个答案:

没有答案