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) {
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?
spring spring-mvc validation service dto
Benjamin m
source share