【问题标题】:REST, MVC - In which layer should link creation for Resources happen?REST、MVC - 资源的链接创建应该在哪一层发生?
【发布时间】:2018-10-10 15:53:21
【问题描述】:

以下是我的场景的一个抽象案例。

在通过/customers/:id 端点发出GET 请求后,Controller 中的Request Handler 调用Service 中的函数,该函数返回Customer指定的标识。之后,在Controller中,接收到的Customer被转换为CustomerResourceDTO

    @GetMapping("customers/{id}")
    public ResponseEntity<CourseResourceDTO> getSingleCustomer(@PathVariable int id) {
        Customer customer = customerService.getSingleCustomer(id);
        CustomerResourceDTO customerResourceDTO = new CustomerResourceDTO(customer);
        return new ResponseEntity<>(courseResourceDTO, HttpStatus.OK);
    }

并且在CustomerResourceDTO 构造函数中,也会创建链接。

@Getter @Setter
public class CustomerResourceDTO extends ResourceSupport {
    String firstName;
    String lastName;
    public CustomerResourceDTO (Customer customer) {
        this.firstName = customer.firstName;
        this.lastName = customer.lastName;
        add(new Link("https://linkToSelf").withSelfRel());
    }
}

在 DTO/资源创建中设置链接是一种好习惯,还是应该将其委托给另一个类/层?

【问题讨论】:

  • 链接的目的是什么?它是否与客户相关,例如唯一标识它?需要提供有关链接用例的更多信息以确定其生成层。
  • 链接是找到相应客户的 URI,例如“localhost:8080/customer/1”。通过查看 HATEOAS,您可以找到有关 REST 架构中链接用途的更多信息。我主要关心的是我应该把创建链接的逻辑放在哪里,不管它们的目的是什么。

标签: java spring model-view-controller dto


【解决方案1】:

从富领域模型的角度来看;我在我的 DTO 中添加了以下 方法,它们扩展了 ResourceSupportaddSelfLinkaddLink(添加指向另一个资源的链接),否则,在我看来,它们应该在 Service 中找到一个位置并在 Controller 中调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 2015-01-10
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多