将Spring数据休息链接与同一实体上的控制器链接合并

时间:2016-09-26 08:57:33

标签: spring-boot spring-data-rest hateoas spring-hateoas

我想将HATEAOS链接与Controller和Repository上的方法结合起来。

@RepositoryRestController
@ResponseBody
@ExposesResourceFor(Group.class)
@RequestMapping(value = "/api/v2/groups", produces = MediaTypes.HAL_JSON_VALUE)
public class GroupController {

    @Resource
    private GroupService groupService;

    @RequestMapping(value = "/external", method = POST)
    public  @ResponseBody   PersistentEntityResource saveExternalGroup(
            @RequestBody Group newGroup,
            PersistentEntityResourceAssembler assembler) {

        return assembler.toResource(groupService.saveExternalGroup(newGroup));

    }

}

存储库:

@RepositoryRestResource(excerptProjection = GroupSummary.class)
public interface GroupDao extends DefaultDao<Group, Long> {

    @NotNull
    List<Group> findByState(@Nullable GroupState state);
...other methods...

我想实现有可能转到/ api / v2 / groups并且还有链接到/ external。目前,只返回来自存储库的链接:

"_links": {
    "first": {
      "href": "http://localhost:8300/api/v2/groups?page=0&size=20"
    },
    "self": {
      "href": "http://localhost:8300/api/v2/groups"
    },
    "next": {
      "href": "http://localhost:8300/api/v2/groups?page=1&size=20"
    },
    "last": {
      "href": "http://localhost:8300/api/v2/groups?page=1&size=20"
    },
    "profile": {
      "href": "http://localhost:8300/api/v2/profile/groups"
    },
    "search": {
      "href": "http://localhost:8300/api/v2/groups/search"
    }
  },

我应该如何实现上述所有内容以及类似的内容:

"external": {
          "href": "http://localhost:8300/api/v2/groups/external"
        }

或者“/ external”是POST有问题吗?如果是这样,请用“method = GET”评论并考虑这个问题。

1 个答案:

答案 0 :(得分:0)

选项1:

如果它是一次性的,您可以使用Resource类在控制器方法中添加链接。

@RequestMapping(value = "/external", method = POST)
public  @ResponseBody   PersistentEntityResource saveExternalGroup(
        @RequestBody Group newGroup,
        PersistentEntityResourceAssembler assembler) {

    PersistentEntityResource resource = assembler.toResource(groupService.saveExternalGroup(newGroup));

    // Replace with ControllerLinkBuilder call, or EntityLinks as you see fit.
    resource.add(new Link("http://localhost:8300/api/v2/groups/external","search"));

    return resource;
}

选项2:

如果您希望将此链接添加到每个呈现的Resource<Group>,请创建一个ResourceProcessor组件以添加它。

@Component
public class GroupResourceProcessor implements ResourceProcessor<Resource<Group>> {

    @Override
    public Resource<Group> process(Resource<Group> groupResource) {

        // Replace with ControllerLinkBuilder call, or EntityLinks as you see fit.
        groupResource.add(new Link("http://localhost:8300/api/v2/groups/external","search"));

        return groupResource;
    }

}