在服务或控制器中进行Spring DTO验证? [英] Spring DTO validation in Service or Controller?

查看:270
本文介绍了在服务或控制器中进行Spring DTO验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Spring构建直接的AJAX/JSON Web服务.常见的数据流是:

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批注在@Controller方法中可以很好地工作.
  • 为什么@Valid 不能@Service方法中起作用?
  • I know the @Valid annotation which works pretty well inside @Controller methods.
  • Why does @Valid not work within @Service methods?

我的意思是:任何其他服务和控制器都可以使用一种服务方法.因此,在@Service级别进行验证不是更有意义吗?

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:

MyDTO.java:

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

MyServiceImpl.java:

MyServiceImpl.java:

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

MyController.java:

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);
}


服务方法接收DTO是惯例吗?


Is it common practice that the service method receives the DTO?

  • 如果yes:在服务方法中验证DTO的最佳实践是什么?
  • 如果no:也许控制器应该操纵Domain对象并只让服务保存该对象? (这对我来说似乎毫无用处)
  • If yes: What's the best practice to validate that DTO inside the service method?
  • If 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.

您如何解决这个问题?

推荐答案

我的答案?两者.

该服务必须检查其自身合同的有效性.

The service must check its own contract for validity.

控制器是UI的一部分.它应该进行验证和绑定以获得更好的用户体验,但是服务不应依赖它.

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.

该服务无法知道其调用方式.如果将其包装为REST服务怎么办?

The service cannot know how it's being called. What if you wrap it as a REST service?

该服务还以任何UI都无法知道的方式了解业务逻辑违规.它需要进行验证以确保用例得到适当满足.

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.

双袋装;两者都做.

这篇关于在服务或控制器中进行Spring DTO验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆