0

lately I was trying to understand how spring processes @Valid annotation. For example look at the following controller's method:

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createEmployee(@Valid EmployeeForm form, Errors errors) {
    if(errors.hasErrors()) {
         //validation errors
    }
    //method code
}

I am struggling to understand how errors instance is getting populated with validation errors in real-time. Does Spring, during compilation of the controller, inject code responsible for validation at the beginning of the createEmployee method? If so how this code would look?

I really tried to find an example of how this validation is performed in real life but it's just impossible. Help me please.

Rustam Issabekov
  • 3,279
  • 6
  • 24
  • 31

1 Answers1

1

Everything happens at runtime. See the reference for more details on doing validation or this post for extra explanations.

Basically this is part of how Spring works internally. When you start your application Spring registers some beans, bean processors, can scan your classpath for annotated classes, registers those found annotated classes, builds proxies for some of them etc and uses all of them to build a context.

When handling a request, the request is handled on some predetermined execution path that starts with the DispatcherServlet, picking up other beans from the context as needed to handle the request (like validation for example) then forwarding to you controller in the createEmployee (which was registered as startup because Spring found your @RequestMapping annotations on your controller). When you return from the method the flow continues by building a model, selecting a view to display and then generating the response to the client.

For your example, Spring basically finds the @Valid annotation, looks for an already configured validator (configured by you or by a provided implementation for e.g. JSR-303), runs the validator and stores the validation result inside the Errors object. It does this when the request is processed, as mentioned above, it does not generate code.

If your question is to know exactly how Spring does this, in all it's details, you could take the Spring source code and have a look/debug it.

Community
  • 1
  • 1
Bogdan
  • 23,890
  • 3
  • 69
  • 61