【问题标题】:Using RepositoryRestResource annotation to change RESTful endpoint not working使用 RepositoryRestResource 注释更改 RESTful 端点不起作用
【发布时间】:2015-10-15 00:58:26
【问题描述】:

我是 Spring Boot 的新手。我试图创建也插入 MongoDB 的 RESTful Web 服务。 除此以外,一切正常,如指南所述。

package hello.requests;

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import hello.models.CustomerModel;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface CustomerRepository extends MongoRepository<CustomerModel, String> {

    List<CustomerModel> findByLastName(@Param("name") String name);

}

在这里,我尝试将存储库的 RESTful 端点从默认的 /customerModels 更改为 /people。但是当我运行它时,如果我尝试/people,我会得到 404,但对于/customerModels 效果很好。 在更广泛的意义上,@RepositoryRestResource 是如何工作的? 我在这里做错了什么?

【问题讨论】:

  • 你能分享你的配置吗?
  • 您能详细说明一下吗?这或多或少基于此 Spring 指南。 spring.io/guides/gs/accessing-mongodb-data-rest
  • 你检查过你的 mongodb 集合“人”吗?顺便说一句,如果遇到 404 异常,您能否分享有关它的日志。
  • 没有 MongoDB 集合“人”。该集合保存为“CustomerModels”。 collectionResourceRel = "people", path = "people" 用于将端点从 /customerModels 别名为 /people。引自指南。 ` @RepositoryRestResource 对于要导出的存储库来说不是必需的。它仅用于更改导出详细信息,例如使用 /people 代替 /persons 的默认值。`
  • 好的,你试过这样collectionResourceRel = "CustomerModels", path = "people" 吗?

标签: java spring mongodb rest spring-boot


【解决方案1】:

path 属性中不能使用斜线,但可以在application.properties 中设置基本路径:

# DATA REST (RepositoryRestProperties)
spring.data.rest.base-path=/my/base/uri
# Base path to be used by Spring Data REST to expose repository resources.

【讨论】:

    【解决方案2】:

    如果不查看您的整个配置,就很难准确了解您的情况。但是,使用https://github.com/spring-guides/gs-accessing-data-mongodb.git 的最新指南,我可以通过进行以下更改使其正常工作:

    • 在 POM 文件中添加 spring-boot-starter-data-rest 作为依赖项。

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-rest</artifactId>
      </dependency>
      
    • 将此注释添加到 CustomerRepository 类。

      @RepositoryRestResource(path = "people")
      
    • 在 Customer 类中为构造函数中的 2 个名称字段设置 getter 和 setter,以避免 Jackson 序列化错误。

    当我运行应用程序时使用它,我可以访问位于http://localhost:8080/people 的存储库。如果我删除注释,则可以在 http://localhost:8080/customers 访问 CustomerRepository。如果你想让我在 GitHub 上发布一个分支,请告诉我。

    回答您关于 RepositoryRestResource 是什么的问题,它会覆盖默认创建的 ResourceMapping 的属性。它的属性用于创建映射并更改映射类上方法的相关返回值。默认情况下,Spring Data Rest 根据存储库定义中使用的对象的类名创建默认值。

    【讨论】:

      【解决方案3】:

      /customerModels 是默认生成的,因为您的默认方法返回CustomerModel 的列表。因此,您可以尝试将此 @RestResource(path = "names") 添加到您的方法中,然后像这样访问它: http://localhost:8080/yourapp/people/search/names。看这里:Spring data docs

      【讨论】:

        猜你喜欢
        • 2016-12-10
        • 2020-08-31
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 2019-10-02
        • 2015-03-18
        • 1970-01-01
        • 2013-09-20
        相关资源
        最近更新 更多