40

I am validating my POJOs in a REST resource endpoint in Jersey:

public class Resource {
    @POST
    public Response post(@NotNull @Valid final POJO pojo) {
        ...
    }
}

public class POJO {
    @NotNull
    protected final String name;

    @NotNull
    @Valid
    protected final POJOInner inner;

    ...
}

public class POJOInner {
    @Min(0)
    protected final int limit;

    ...
}

This seems to work fine.

However, the @Min(0) annotation is only verified if the field inner has the @Valid annotation. It doesn't feel right to add the @Valid annotation to each field which isn't a primitive.

Is there a way to tell the bean validator to automatically recursively continue the validation, even when no @Valid annotation is present? I would like my POJO to be as following:

public class POJO {
    @NotNull
    protected final String name;

    @NotNull
    protected final POJOInner inner;

    ...
}
Anish B.
  • 9,111
  • 3
  • 21
  • 41

1 Answers1

28

Actually, according to the specification, adding @Valid is exactly for this usecase. From the JSR 303 specification:

In addition to supporting instance validation, validation of graphs of object is also supported. The result of a graph validation is returned as a unified set of constraint violations. Consider the situation where bean X contains a field of type Y. By annotating field Y with the @Valid annotation, the Validator will validate Y (and its properties) when X is validated.

...

The @Valid annotation is applied recursively

Erwin de Gier
  • 632
  • 7
  • 12
  • 4
    Spring does not do this by default.. i'm using spring boot 2.0.0.BUILD-SNAPSHOT – Gonçalo Feb 20 '17 at 14:58
  • 16
    While this might be true it does not explain if it is possible to achieve recursive validation without needing to annotate all members, which is what OP is asking.. – cen May 14 '17 at 15:16
  • What resolves this IMO is obtaining a custom validator and adding a TraversableResolve as in https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-bootstrapping.html#example-traversable-resolver This would be better than cluttering the codebase with `@Valid` annotations if the intent it to validate the whole object graph. – HackerMonkey Mar 03 '19 at 12:05
  • 2
    "The @Valid annotation is applied recursively" it does not seem to in hibernate implementation though... – Klesun Apr 09 '20 at 19:33
  • [JSR 303](https://download.oracle.com/otn-pub/jcp/bean_validation-1.0-fr-oth-JSpec/bean_validation-1_0-final-spec.pdf) – Klesun Apr 09 '20 at 19:33