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

Cod*_*ley 17 java rest spring mongodb spring-boot

我是Spring boot的新手.我正在尝试创建RESTful Web服务,该服务也插入到MongoDB中.除了这个以外,指南解释的一切都很好.

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);

}
Run Code Online (Sandbox Code Playgroud)

在这里,我试图将存储库的RESTful端点从默认更改/customerModels/people.但是当我运行这个时,如果我尝试,我会得到404,/people但是可以正常工作/customerModels.从广义上讲,如何@RepositoryRestResource运作?我在这做错了什么?

wil*_*oop 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.
Run Code Online (Sandbox Code Playgroud)


Rob*_*ily 6

如果没有看到整个配置,很难确切知道您的情况发生了什么.但是,使用https://github.com/spring-guides/gs-accessing-data-mongodb.git上的最新指南,我可以通过进行以下更改来使其工作:

  • 将spring-boot-starter-data-rest添加为POM文件中的依赖项.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    
    Run Code Online (Sandbox Code Playgroud)
  • 将此批注添加到CustomerRepository类.

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

在运行应用程序时使用此功能,我可以访问http:// localhost:8080/people的存储库.如果我删除了注释,则在http:// localhost:8080/customers访问CustomerRepository .如果你想让我在GitHub上发帖子,请告诉我.

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