REST,MVC-应该在哪个层创建资源链接?

时间:2018-10-10 15:53:22

标签: java spring model-view-controller dto

以下是我的情况的抽象情况。

GET端点上发出/customers/:id请求之后,控制器中的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 /资源创建中设置链接是一种好习惯,还是应该将其委托给另一个类/层?

1 个答案:

答案 0 :(得分:0)

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