【问题标题】:Spring Boot Starter Data Rest change URL of repository from the root URISpring Boot Starter Data Rest 从根 URI 更改存储库的 URL
【发布时间】:2014-06-16 02:54:51
【问题描述】:

按照此处的 spring.io 示例:http://spring.io/guides/gs/accessing-data-rest/ 将存储库公开为 REST Web 服务工作得很好,但我看不到如何更改公开服务的 URL。 API 文档对于注解参数的含义有些模糊,可能是假设了一些先验知识。

我想要什么 - 在 http://localhost:8080/api/people 访问的 HATEOAS 服务,用于 People 存储库。我想只使用注释来实现这个 URL,而不是弄乱上下文根或类似的东西。我尝试了以下存储库注释:

  • @RepositoryRestResource(collectionResourceRel = "api/people", path = "people")
  • @RepositoryRestResource(collectionResourceRel = "people", path = "api/people")
  • @RepositoryRestResource(collectionResourceRel = "api/people", path = "api/people")

这些都不起作用。

我知道我可能错过了明显的,非常感谢任何能指出它的人。

【问题讨论】:

标签: rest spring-boot


【解决方案1】:

Spring Boot 1.2 开始,您可以设置此属性:

spring.data.rest.baseUri=api

或者:

spring.data.rest.base-uri=api

(Spring Boot 使用relaxed binding 系统)

注意:我发现如果你用自定义配置扩展RepositoryRestMvcConfiguration,该属性不会生效。欲了解更多信息,请参阅:

https://github.com/spring-projects/spring-boot/issues/2392

一旦下一个版本的 Spring Boot 发布(1.2.1 之后),解决方案将改为扩展 RepositoryRestMvcBootConfiguration

【讨论】:

  • 在属性中设置它与在扩展 RepositoryRestMvcConfiguration 的类中设置它有什么真正的优势吗?
  • 它有点干净和弹性,因为你可能有一个应用程序属性文件。在代码中做这件事需要更多的打字和更多的代码来测试。依赖 spring 约定意味着您不需要测试自己的代码或拥有不同的属性。最后,它使新开发人员的加入变得更加容易,因为它是标准约定而不是自定义代码。对于这个属性本身来说可能没什么大不了,但它的原理就是
  • @adam0404 - 两者都可以根据 Spring Boot 的属性加载器工作。
【解决方案2】:

从 Spring Boot 1.4.3 开始,代码应该是:

spring.data.rest.base-path:api

(我认为 baseUri 自 1.2.3 起已弃用)

【讨论】:

  • 欢迎来到 SO。如果您还没有阅读,请阅读此how-to-answer
【解决方案3】:

虽然我无法使用注释 @RepositoryRestResource 结合 CrudRepository 更改 REST 服务的基本路径,但我设法使用 JpaRepository 和带有注释 @RequestMapping 的自定义控制器来做到这一点。

存储库可能类似于:

@Repository
interface PersonRepository : JpaRepository<Person, Long>

还有控制器:

@RestController
@RequestMapping("/api/people")
class PersonRestController(private val personRepository: PersonRepository) {
    ...

另一方面,您可以在项目的 application.properties 文件中更改所有 REST 服务的基本路径并对其进行修改。添加行:

# DATA REST (RepositoryRestConfiguration)
spring.data.rest.base-path = api

api 更改为您希望在URL 中使用的路径。第一行是注释,因此它不是强制性的,但有助于标记配置值的性质以供将来参考。

您可以在文档的Appendix A 中找到 Spring Boot 2.0.1 的所有常用应用程序属性。

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2021-01-18
    • 2021-02-09
    相关资源
    最近更新 更多