【问题标题】:Expose custom endpoint to base-path in Spring Boot Data Rest在 Spring Boot Data Rest 中将自定义端点暴露给基本路径
【发布时间】:2019-08-03 04:57:17
【问题描述】:

我正在使用 Spring Boot Data Rest,我可以使用以下 url 列出所有端点:

http://localhost:8080/api

它列出了以下端点:

{
"_links": {
    "tacos": {
        "href": "http://localhost:8080/api/tacos{?page,size,sort}",
        "templated": true
    },
    "orders": {
        "href": "http://localhost:8080/api/orders"
    },
    "ingredients": {
        "href": "http://localhost:8080/api/ingredients"
    },
    "profile": {
        "href": "http://localhost:8080/api/profile"
    }
}

}

但我在 Controller 中创建了一个自定义端点,如下所示

@RepositoryRestController
public class RecentTacosController {

private TacoRepository tacoRepo;

public RecentTacosController(TacoRepository tacoRepo) {
    this.tacoRepo = tacoRepo;
}

@GetMapping(path = "/tacos/recent", produces = "application/hal+json")
public ResponseEntity<Resources<TacoResource>> recentTacos() {

    PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
    List<Taco> tacos = tacoRepo.findAll(page).getContent();
    List<TacoResource> tacoResources = new TacoResourceAssembler().toResources(tacos);
    Resources<TacoResource> recentResources = new Resources<TacoResource>(tacoResources);
    recentResources.add(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(RecentTacosController.class).recentTacos()).withRel("recents"));
    return new ResponseEntity<>(recentResources, HttpStatus.OK);
}

}

但在基路径上执行 GET 时,此端点 (http://localhost:8080/api/tacos/recent) 未列出。

【问题讨论】:

    标签: spring-boot spring-data-rest


    【解决方案1】:

    在你的一个类中实现ResourceProcessor&lt;RepositoryLinksResource&gt;(可能是控制器本身),添加以下方法:

      @Override
      public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add( ... );
        return resource;
      }
    

    ...并在那里创建并添加正确的链接到您的自定义方法。

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 2021-03-11
      • 2017-09-14
      • 2018-03-17
      • 2017-09-18
      • 2019-07-09
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多