使用RepositoryRestResource注解来更改RESTful端点不起作用

17

我是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是如何工作的? 我在这里做错了什么?


你能分享一下你的配置吗? - İlker Korkut
你能详细说明一下吗?这个与Spring指南比较类似。 https://spring.io/guides/gs/accessing-mongodb-data-rest/ - Codevalley
你检查了你的 MongoDB 集合 "people" 吗?顺便问一下,如果出现 404 错误,你能分享一下日志吗? - İlker Korkut
没有名为“People”的MongoDB集合。该集合被保存为“CustomerModels”。 collectionResourceRel =“people”,path =“people”用于将端点从/customerModels别名为/people。引用指南中的内容。 @RepositoryRestResource不是必须导出存储库的。它仅用于更改导出详细信息,例如使用/people而不是默认值/persons。 - Codevalley
好的,你试过这样写吗 collectionResourceRel = "CustomerModels", path = "people" - İlker Korkut
3个回答

7

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.

6

没有看到您的完整配置,很难知道您的情况发生了什么。但是,使用https://github.com/spring-guides/gs-accessing-data-mongodb.git上最新的指南,我能够通过进行以下更改使其正常运行:

  • Adding spring-boot-starter-data-rest as a dependency in the POM file.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    
  • Adding this annotation to the CustomerRepository class.

    @RepositoryRestResource(path = "people")
    
  • Setting up getters and setters in the Customer class for the 2 name fields in the constructor to avoid a Jackson serialization error.

使用这个注解后,当我运行应用程序时,我能够访问位于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 文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接