Home » Java » Why are @Valid annotations ignored on MultipartFile objects in Spring?

Why are @Valid annotations ignored on MultipartFile objects in Spring?

Posted by: admin October 22, 2018 Leave a comment

Questions:

This is a spin-off from a previous question, Spring validator class is ignored by controller. I’m struggling to make my controller accept a MultipartFile object and make Spring bind a Validator to this object. Succintly, this does not work:

@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
    }
}

I’m not the first person on the world wide web to face a similar problem.

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

All examples solve my problem my wrapping the MultipartFile in a very dumb wrapper class in order for the @Valid annotation to work. It seems as if this is necessary, but why is this necessary? I must emphasize that this particular question is not about working around my technical problem, but to understand what it is about MultipartFile that makes these objects ignored by the @Valid annotation.

Answers: