java - 使用 Spring Data REST 的自定义 Controller 隐藏默认端点

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

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

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

我有一个自定义 Controller :

@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]+}")

通过这种方式,我的 Controller 无法捕获 url localhost:8080/api/v1/creditTransfers/search 但是,如果我仅覆盖 DELETE 方法,当我尝试 GET localhost:8080/api/v1/creditTransfers 我收到错误不支持请求方法“GET”。似乎我的 Controller 覆盖了特定路径的所有方法,而不仅仅是我设置的方法。

最佳答案

如本thread中所述,原来 here ,如果您使用 @RepositoryRestController@RequestMapping 注释您的 Controller ,您将失去 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 .

关于java - 使用 Spring Data REST 的自定义 Controller 隐藏默认端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47557276/

相关文章:

java - 将 java.lang.String 类型映射到 Postgres JSON 类型

java - 如何使用我的 .properties 文件中的自定义消息,但使用 @Size 注释提供的参数?

java - Spring-Data-JPA - 将一条记录插入数据库后无限递归

spring - service-dao 模式的最佳实践是什么?

spring - 尝试运行 npm run build 时出错

java - Android - 尝试在不使用移动网络的情况下向自己发送虚假短信

java - J2SE 上的 DataSource 和 DriverManager

java - Spring中的Json错误

java - Spring bean messageSouce不能同时在ApplicationConfig和WebMvcConfig中

java - Try and Catch 用于简单的计算器输入