gpt4 book ai didi

java - REST、MVC - 资源链接创建应在哪一层发生?

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:42 24 4
gpt4 key购买 nike

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

通过 /customers/:id 端点发出 GET 请求后,Controller 中的Request Handler 会调用 Service 中的一个函数,该函数返回具有指定 ID 的 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/资源创建中设置链接是一个好习惯吗?还是应该将其委托(delegate)给另一个类/层?

最佳答案

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

关于java - REST、MVC - 资源链接创建应在哪一层发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com