首页 > 解决方案 > 如何自定义 Spring Data REST 以使用存储库资源的自定义路径?

问题描述

我正在使用 SPRING DATA REST 开发一个微服务,我需要子资源才能通过主要资源访问,如下所示:

http://localhost:8080/posts
http://localhost:8080/posts/1/comments

并像这样直接阻止对子资源的直接访问http://localhost:8080/comments/*

只有通过相关的帖子才能访问评论,我在我的存储库中做了以下操作:

@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {
   ...
}

评论:

 @RepositoryRestResource(collectionResourceRel = "comments", path = "comments")
    public interface CommentRepository extends PagingAndSortingRepository<Comment, Long> {
       ...
    }

现在默认情况下,当我转到时,SPRING DATA REST 返回以下结果:http://localhost:8080

{
  "id": 1,
  "content": "some post text .........................",
  "author":"abc",
  
  "_links": {
    "self": {
      "href": "http://localhost:8080/posts/1"
    },
    "attributes": {
      "href": "http://localhost:8080/posts/1/comments"
    }
  }
}

现在,如果我想发表评论,我需要执行以下操作:

 http://{server:port}/comment METHOD:POST
    
    {"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}

但我需要实现的是 POST 到这样的 url http://{server:port}/posts/1/comment,其中POST 是根资源, 不像以前的路径 http://{server:port}/comment

 http://{server:port}/posts/1/comment METHOD:POST
    
{"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}

我现在如果创建自定义评论 @controller,这是可能的,但我想使用 SPRING DATA REST 和 Hateoas 支持的已经构建的功能。

标签: spring-bootspring-data-jpaspring-dataspring-data-restspring-hateoas

解决方案


推荐阅读