Spring DTO check in a service or controller?

I am creating a direct AJAX / JSON web service using Spring. Total data stream:

some DTO from browser v Spring @Controller method v Spring @Service method 

I am looking for the easiest way to handle data validation.

  • I know the @Valid annotation, which works well inside @Controller methods.
  • Why @Valid n't @Valid work in @Service methods?

I mean: the service method can be used by any other service and controller. So it makes no sense to justify the @Service level?


Take this simple example:

MyDTO.java:

 public class MyDTO { @NotNull public String required @Min(18) public int age; } 

MyServiceImpl.java:

 public MyDomainObject foo(MyDTO myDTO) { // persist myDTO // and return created domain object } 

MyController.java:

 @Autowired MyService myService; @Autowired // some simple bean mapper like Dozer or Orika Mapper mapper; // for converting domain objects to DTO @RequestMapping(...) public MyDomainObjectDTO doSomething(@RequestBody MyDTO myDTO) { mapper.map(myService.foo(myDTO), MyDomainObjectDTO.class); } 

Is it common practice that a service method gets a DTO?

  • If yes : What is the best practice for checking this DTO inside a service method?
  • If no : Maybe the controller should manipulate the Domain object and just let the service save that object? (it seems useless to me)

In my opinion, a service should only be responsible for data consistency.

How do you solve this?

+7
spring spring-mvc validation service dto
source share
2 answers

My answer? Both.

The service must validate its own contract.

The controller is part of the user interface. It should check and link for a better user experience, but the service should not rely on it.

The service cannot know how to call it. What if you wrap it as a REST service?

The service also knows about business logic violations in a way that the user interface cannot. It must be checked to ensure that the use case is being properly implemented.

Double pack; do both.

+10
source share

See my other answer: Check the prerequisites at the controller or service level

If you really want to do validation, for example error handling at your service level, similar to Spring MVC, you can use javax.validation and AspectJ (to advise validation methods), which I do because I like to reflect the work and declarative programming ( annotations).

Spring MVC does not need to do AspectJ / AOP to handle errors, because methods are invoked through reflection (routing / dispatching URLs).

Finally, for you MVC code, you should know that @Valid is kind of unofficial deprecated. Instead, consider @Validated , which will use more features of javax.validation .

+2
source share

All Articles