Use @Validated and @Valid with spring validator
<p>I have a java bean being used to send JSON messages to a spring <code>@RestController</code> and I have bean validation setup and running just fine using <code>@Valid</code>. But I want to move to Protobuf/Thrift and move away from REST. It is an internal API and a lot of big companies have done away with REST internally. What this really means is that I no longer have control of the message objects - they are generated externally. I can't put annotations on them anymore.</p>

<p>So now my validation has to be programmatic. How do I do this? I have coded up a <code>Validator</code> and it works just great. But it doesn't use the nice <code>@Valid</code> annotation. I have to do the following:</p>

<pre><code>@Service
public StuffEndpoint implements StuffThriftDef.Iface {

    @Autowired
    private MyValidator myValidator;

    public void things(MyMessage msg) throws BindException {
        BindingResult errors = new BeanPropertyBindingResult(msg, msg.getClass().getName());
        errors = myValidator.validate(msg);
        if (errors.hasErrors()) {
            throw new BindException(errors);
        } else {
            doRealWork();
        }
    }
}
</code></pre>

<p>This stinks. I have to do this in every single method. Now, I can put a lot of that into one method that throws <code>BindException</code> and that makes it one line of code to add to every method. But that's still not great.</p>

<p>What I want is to see it look like this:</p>

<pre><code>@Service
@Validated
public StuffEndpoint implements StuffThriftDef.Iface {

    public void things(@Valid MyMessage msg) {
        doRealWork();
    }
}
</code></pre>

<p>And still get the same result. Remember, my bean has no annotations. And yes, I know I can use the <code>@InitBinder</code> annotation on a method. But that only works for web requests.</p>

<p>I don't mind injecting the correct <code>Validator</code> into this class, but I would prefer if my ValidatorFactory could pull the correct one based on the <code>supports()</code> method.</p>

<p>Is this possible? Is there a way to configure bean validation to actually use Spring validation instead? Do I have to hijack a Aspect somewhere? Hack into the <code>LocalValidatorFactory</code> or the <code>MethodValidationPostProcessor</code>?</p>

<p>Thanks.</p>