【问题标题】:How to mix Spring Data Repositories and Spring Rest Controllers如何混合使用 Spring Data Repositories 和 Spring Rest Controllers
【发布时间】:2015-02-07 20:54:33
【问题描述】:

目前,我将一些 Spring Data Repositories 公开为 RESTful 服务,方法是使用 @RepositoryRestResource 注释它们,如下所示:

@RepositoryRestResource(collectionResourceRel = "thing1", path = "thing1")
public interface Thing1Repository extends PagingAndSortingRepository<Thing1, String> {}

@RepositoryRestResource(collectionResourceRel = "thing2", path = "thing2")
public interface Thing2Repository extends CrudRepository<Thing2, String> {}

这一切都很好。当您点击我的第一个端点时,还会显示我公开的所有 Spring Data Repositories,如下所示:

{
   _links: {
      thing1: {
         href: "http://localhost:8080/thing1{?page,size,sort}",
         templated: true
      },
      thing2: {
         href: "http://localhost:8080/thing2"
      }
   }
}

现在我想公开一些不能由 Spring Data Repositories 表示的端点,所以我使用的是 RestController。

这是一个简单的例子:

@RestController
@ExposesResourceFor(Thing3.class)
@RequestMapping("/thing3")
public class Thing3Controller {

  @Autowired 
  EntityLinks entityLinks;

  @Autowired 
  Thing3DAO thing3DAO;

  //just assume Thing3.class extends ResourceSupport. I know this is wrong, but it makes the example shorter  
  @RequestMapping(value = "/{id}", produces = "application/json")
  Thing3 thing3(@PathVariable("id") String id)
  {
      Thing3 thing3 = thing3DAO.findOne(id);         

      Link link = entityLinks.linkToSingleResource(Thing3.class, id);
      thing3.add(link);

      return thing3;
  }
}

现在如果我运行这个应用程序并转到:

http://localhost:8080/thing3/{id} 

我确实得到了 Thing3 的 JSON 表示形式,其中包含指向自身的链接,它按预期工作。

我想弄清楚如何让第一个端点也描述这个控制器。我基本上想要这个:

{
   _links: {
      thing1: {
         href: "http://localhost:8080/thing1{?page,size,sort}",
         templated: true
      },
      thing2: {
         href: "http://localhost:8080/thing2"
      },
      thing3: {
         href: "http://localhost:8080/thing3"
      }
   }
}

我需要做什么才能让我的基础端点拥有到此控制器的链接?

【问题讨论】:

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


【解决方案1】:

您可以覆盖 RepositoryLinkResource,并添加一个指向您的东西的资源:

resource.add(ControllerLinkBuilder.linkTo(Thing3Controller.class).withRel("thing3"));

检查这个问题:Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2023-03-23
    • 2017-11-10
    • 2014-02-12
    • 2013-02-20
    相关资源
    最近更新 更多