java – 如何混合Spring数据存储库和Spring Rest控制器

目前,我将一些Spring数据存储库作为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数据库,像这样:

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

现在我有一些我想要公开的端点,它不能被Spring数据存储库表示,所以我正在使用一个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"
      }
   }
}

我需要做些什么来让我的基本端点有一个链接到这个控制器?

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

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

翻译自:https://stackoverflow.com/questions/27387856/how-to-mix-spring-data-repositories-and-spring-rest-controllers

转载注明原文:java – 如何混合Spring数据存储库和Spring Rest控制器