我正在使用 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
}
}
旁注:我还使用了映射快捷方式 GetMapping和 DeleteMapping .
关于java - 使用 Spring Data REST 的自定义 Controller 隐藏默认端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47557276/