Spring 3.2 validation on generic types


I have an interface which looks like this:

public interface Service<T extends Foo, N extends Bar> {
    T doStuff(@Valid N bar);

And another one extending it:

public interface PhoneService extends Service<PhoneFoo, PhoneBar> {

My objects Foo and PhoneFoo look like this (and Bar and PhoneBar are similar) :

public abstract class Foo {

    @NotBlank(message = "Missing id")
    @Size(max = 50, message = "Invalid id")
    private String id;

public class PhoneFoo extends Foo {
    @NotBlank(message = "Missing number")
    @Size(max = 50, message = "Invalid number")
    private String number;

Finally, I basically have a controller implementing PhoneService, such as:

public final class PhoneServiceController implements PhoneService {
    PhoneFoo doStuff(@RequestBody final PhoneBar bar) {
        // Do things...

Now, the validation on the controller just doesn't work at all. I can put an empty id, or an empty number, and no exception will be raised. Is there something special to do for Spring to validate generic types? Any workaround? Is this resolved with Spring boot?

Edit: I do have the following beans defined as well, so that Spring can pick up on validation:

public static MethodValidationPostProcessor methodValidationPostProcessor() {
    MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
    return postProcessor;

public static Validator validator() {
    HibernateValidatorConfiguration configuration = (HibernateValidatorConfiguration) Validation
    return configuration
                    new ValueFormatterMessageInterpolator(configuration

Note: Validation in my project used to work fine, before I introduced a generic interface. It seems to me that Spring doesn't know how to handle @Valid N bar. Or am I wrong?

Show source
| generics   | java   | validation   | spring   | spring-mvc   2017-01-06 21:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 23:01

    To add validation to your service methods, you'll need to add an instance of MethodValidationPostProcessor.

    @ConditionalOnMissingBean(type = "javax.validation.Validator")
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    @ConditionalOnMissingBean(type = "org.springframework.validation.beanvalidation.MethodValidationPostProcessor")
    public MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        return methodValidationPostProcessor;

    @see http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/beanvalidation/MethodValidationPostProcessor.html

◀ Go back