繁体   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