I'm building a straight forward AJAX / JSON web service with Spring. The common data flow is:
some DTO from browser
v
Spring @Controller method
v
Spring @Service method
I'm looking for the most easy way to handle data validation.
@Valid
annotation which works pretty well inside @Controller
methods.@Valid
not work within @Service
methods?I mean: A service method can be used by any other service and controller. So wouldn't it make much more sense to validate at @Service
level?
Let's 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 the service method receives the DTO?
yes
: What's the best practice to validate that DTO inside the service method?no
: Should maybe the controller manipulate the Domain object and just let the service save that object? (this seems pretty useless to me)In my opinion the service should be responsible for only data consistency.
How do you solve this?
My answer? Both.
The service must check its own contract for validity.
The controller is part of the UI. It should validate and bind for a better user experience, but the service should not rely on it.
The service cannot know how it's being called. What if you wrap it as a REST service?
The service also knows about business logic violations in a way that no UI can. It needs to validate to make sure that the use case is fulfilled appropriately.
Double bag it; do both.