【问题标题】:Custom controller with Spring Data REST hide default endpoints具有 Spring Data REST 的自定义控制器隐藏默认端点
【发布时间】:2018-05-13 10:15:15
【问题描述】:

我正在使用 Spring Boot、Spring Data REST、Spring HATEOAS、Hibernate、JPA。

我在我的应用程序中广泛使用 Spring Data REST,并公开了我的实体的所有存储库。 不幸的是,有些特殊情况并不那么容易管理。 其中之一是:

我有一个自定义控制器:

@Api(tags = "CreditTransfer Entity")
@RepositoryRestController
@RequestMapping(path = "/api/v1")
@PreAuthorize("isAuthenticated()")
public class CreditTransferController {

@RequestMapping(method = RequestMethod.GET, path = "/creditTransfers/{id}")
    public ResponseEntity<?> findAll(@PathVariable("id") long id, HttpServletRequest request, Locale locale,
            PersistentEntityResourceAssembler resourceAssembler) {
        //my code

    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/creditTransfers/{id}")
    public ResponseEntity<?> deleteMovement(@PathVariable("id") long id, HttpServletRequest request, Locale locale,
            PersistentEntityResourceAssembler resourceAssembler) {
        //my code
    }

这里的问题是覆盖这些端点,我隐藏了 Spring Data REST 创建的 /search 端点。这对我来说非常重要。

在不干扰 Spring Data REST 提供的默认端点的情况下,我没有找到任何聪明的方法来使其工作。

有没有办法解决我的问题?

================================================ ========================

一个小的改进是使用这样的映射:

@RequestMapping(method = RequestMethod.DELETE, path = "/creditTransfers/{id:[0-9]+}")

通过这种方式,我的控制器不会捕获 url localhost:8080/api/v1/creditTransfers/search,但如果我只覆盖 DELETE 方法,当我尝试 GET localhost:8080/api/v1/creditTransfers 时,我会遇到错误 Request method 'GET' not supported。似乎我的控制器覆盖了特定路径的所有方法,而不仅仅是我设置的方法。

【问题讨论】:

  • 你想不通过控制器覆盖存储库 URL 吗?
  • @AmrAlaa 我还需要覆盖实现。实际上我需要重写 DELETE 的实现。 url 与 Spring Data REST 提供的默认存储库相同。这就是问题所在。

标签: java spring spring-mvc spring-boot spring-data-rest


【解决方案1】:

你可以添加

@RestResource(exported=false)

在存储库中要覆盖的方法。

【讨论】:

【解决方案2】:

正如 thread 和最初的 here 中所解释的,如果您使用 @RepositoryRestController@RequestMapping 注释您的控制器,您将失去 Spring 为您生成“默认”REST 端点的好处。 防止这种情况发生的唯一方法,即同时获取自动生成的端点和您的自定义端点,是仅使用方法级请求映射:

@Api(tags = "CreditTransfer Entity")
@RepositoryRestController
@PreAuthorize("isAuthenticated()")
public class CreditTransferController {

    @GetMapping("/api/v1/creditTransfers/{id}")
    public ResponseEntity<?> findAll(@PathVariable("id") long id, HttpServletRequest request, Locale locale,
            PersistentEntityResourceAssembler resourceAssembler) {
        //my code

    }

    @DeleteMapping("/api/v1/creditTransfers/{id}")
    public ResponseEntity<?> deleteMovement(@PathVariable("id") long id, HttpServletRequest request, Locale locale,
            PersistentEntityResourceAssembler resourceAssembler) {
        //my code
    }

}

旁注:我还使用了映射快捷方式GetMappingDeleteMapping

【讨论】:

  • 谢谢,你为我节省了很多时间和挫折!
猜你喜欢
  • 2016-02-07
  • 2018-03-17
  • 1970-01-01
  • 2014-11-03
  • 2013-10-15
  • 2015-12-07
  • 2018-05-14
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多