Spring Boot binding and validation error handling in REST controller
<p>When I have the following model with JSR-303 (validation framework) annotations:</p>

<pre><code>public enum Gender {
    MALE, FEMALE
}

public class Profile {
    private Gender gender;

    @NotNull
    private String name;

    ...
}
</code></pre>

<p>and the following JSON data:</p>

<pre><code>{ "gender":"INVALID_INPUT" }
</code></pre>

<p>In my REST controller, I want to handle both the binding errors (invalid enum value for <code>gender</code> property) and validation errors (<code>name</code> property cannot be null).</p>

<p>The following controller method does NOT work:</p>

<pre><code>@RequestMapping(method = RequestMethod.POST)
public Profile insert(@Validated @RequestBody Profile profile, BindingResult result) {
    ...
}
</code></pre>

<p>This gives <code>com.fasterxml.jackson.databind.exc.InvalidFormatException</code> serialization error before binding or validation takes place.</p>

<p>After some fiddling, I came up with this custom code which does what I want:</p>

<pre><code>@RequestMapping(method = RequestMethod.POST)
public Profile insert(@RequestBody Map values) throws BindException {

    Profile profile = new Profile();

    DataBinder binder = new DataBinder(profile);
    binder.bind(new MutablePropertyValues(values));

    // validator is instance of LocalValidatorFactoryBean class
    binder.setValidator(validator);
    binder.validate();

    // throws BindException if there are binding/validation
    // errors, exception is handled using @ControllerAdvice.
    binder.close(); 

    // No binding/validation errors, profile is populated 
    // with request values.

    ...
}
</code></pre>

<p>Basically what this code does, is serialize to a generic map instead of model and then use custom code to bind to model and check for errors.</p>

<p>I have the following questions:</p>

<ol>
<li>Is custom code the way to go here or is there a more standard way of doing this in Spring Boot?</li>
<li>How does the <code>@Validated</code> annotation work? How can I make my own custom annotation that works like <code>@Validated</code> to encapsulate my custom binding code?</li>
</ol>