Sha
Sha

Reputation: 1181

Spring Validation Doesn't Work With Generic Types

In my code block, I just want to validate a controller method with Spring boot @Valid annotation for a generic Pair object. But the validation doesn't work for me.

My Controller method looks like this:

@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public void add(@RequestBody @Valid Pair<AddDto, AddUserDto> pair)
{
    ...
    service.add(pair);
}

Pair object looks like:

public class Pair<F, S>
{
    private F first;
    private S second;
}

AddDto object looks like:

public class AddDto
{
    @NotNull
    private String name;
    @NotEmpty
    private List<String> actionList;

    ...getters, setters
}

AddUserDto object looks like:

public class AddUserDto
{
    @NotNull
    private String name;
    @NotNull
    private Long id;

    ...getters, setters
}

In this case, validation doesn't work for me. Is there any suggestion?

Upvotes: 2

Views: 1966

Answers (1)

Mafor
Mafor

Reputation: 10681

It has nothing to do with generics. The problem is that the Pair class does not define any validation rules. Try changing it to:

public class Pair<F, S>
{
    @Valid
    @NotNull
    private F first;
    @Valid
    @NotNull
    private S second;
}

Upvotes: 2

Related Questions