我想为列表中返回的任何对象返回一个自我引用,所以我这样做:
for(PetModel pet : pets){
pet.add(linkTo(methodOn(PetController.class).getPetById(pet.getId())).withSelfRel());
}
这给了我:
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/pet/{petId}"
}
],
"id": 1,
使用.slash(pet.getId())
Link link = ControllerLinkBuilder
.linkTo(PetController.class)
.slash(pet.getId())
.withSelfRel();
//Add link to singular resource
pet.add(link);
说明:
linkTo()
方法检查PetController类并获得其根映射slash()
方法将petId值添加为链接的路径变量withSelfMethod()
将关系限定为自链接methodOn()
通过在代理控制器上对目标方法进行伪调用来获得方法映射。 methodOn()
是获取方法映射的一种方法,不是必需的部分。