簡體   English   中英

Spring HATEOAS 1.x 上的 ResourceSupport.getId()

[英]ResourceSupport.getId() on Spring HATEOAS 1.x

我正在通過書面教程學習如何使用 Spring Boot 構建 REST API,並且在某些時候使用了 HATEOAS。 由於沒有找到類 Resource、Resources、ControllerLinkBuilder 等,本教程似乎使用了一個現在過時的版本 (0.x),所以經過一番挖掘,我發現 1.x 修改了一些類的結構和命名。 我只是用更新的版本(帶有 EntityModel 的資源等)替換了對類/方法的所有提及,直到我卡在需要資源的“自我”鏈接來生成一個POST 命令的 HTTP 響應:

@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee newEmployee) throws URISyntaxException {

  Resource<Employee> resource = assembler.toResource(repository.save(newEmployee));

  return ResponseEntity
    .created(new URI(resource.getId().expand().getHref()))
    .body(resource);
}

是否有等價物

resource.getId()

對於 HATEOAS 1.x 中的 EntityModel?

這是“匯編程序”變量是一個實例的類:

package payroll;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;

import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;

@Component
class EmployeeResourceAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {

    @Override
    public EntityModel<Employee> toModel(Employee employee) {

        return new EntityModel<>(employee,
                linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
                linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
    }
}

找到了,這相當於在 HATEOAS 1.x 中執行此操作:

return ResponseEntity
                .created(new URI(resource.getLink("self").orElse(new Link("self")).getHref()))
                .body(resource);

由於getLink()返回一個Optional<Link>我只需要添加orElse()案例以便它“解包”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM