如何混合Spring Data Repositories和Spring Rest Controller

时间:2014-12-09 20:08:05

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

目前,我通过使用@RepositoryRestResource注释它们,将一些Spring数据库公开为RESTful服务:

@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"
      }
   }
}

如何让我的基本端点拥有指向此控制器的链接,我需要做什么?

1 个答案:

答案 0 :(得分:13)

您可以覆盖RepositoryLinkResource,并添加指向您的thing3的资源:

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