0

I am having this UserDto class which I want to put under @Valid

@Getter @Setter
public class UserDto{

  @NotEmpty(message = "Name cannot be empty")
  private String name;

  @NotNull(message = "Provide a valid age")
  private Integer age;

}

I have some requirements where I can't put validation on controller method, but I need to do it on the service method.

@PostMapping(value = "/user")
public void create(@RequestBody UserDto user){
  userService.create(user);
}

public void create(@Valid UserDto user){
  System.out.println(user);
}

But this is not working. And if I put @Valid on the controller method, I do get the validation errors as expected.

Why so? Does serialization/deserialization has something to do with valition?

The Coder
  • 3,447
  • 7
  • 46
  • 81
  • Does this answer your question? [How to manually trigger spring validation?](https://stackoverflow.com/questions/28702809/how-to-manually-trigger-spring-validation) – Matt U Dec 15 '19 at 15:20
  • Have no tested but maybe [this](https://stackoverflow.com/q/56759120/6413377) works also: – pirho Dec 15 '19 at 17:08
  • @MattU Why would I need to trigger it manually? It should be handled itself. – The Coder Dec 15 '19 at 19:36
  • @pirho No, same problem – The Coder Dec 15 '19 at 19:37
  • No. The validation annotations are handled by the web layer (controller) when `@Valid` is present because it's configured to do so. The framework knows nothing of a "service layer", only a web layer. The annotation itself is not where the magic happens, so to speak. – Matt U Dec 16 '19 at 00:58
  • Thanks. Manually triggering the validation did resolved the issue. – The Coder Dec 16 '19 at 07:59

0 Answers0