我是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);
}
这里我尝试将存储库的RESTful端点从默认/customerModels
更改为/people
。但是当我运行这个时,如果我尝试/people
,我会得到404,但对/customerModels
工作正常。
从广义上讲,@RepositoryRestResource
如何运作?
我在这里做错了什么?
答案 0 :(得分: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.
答案 1 :(得分: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>
将此注释添加到CustomerRepository类。
@RepositoryRestResource(path = "people")
在Customer类中为构造函数中的2个名称字段设置getter和setter,以避免Jackson序列化错误。
在运行应用程序时使用此功能,我可以在http://localhost:8080/people访问存储库。如果我删除注释,则在http://localhost:8080/customers访问CustomerRepository。如果你想让我在GitHub上发帖子,请告诉我。
要回答有关RepositoryRestResource是什么的问题,它会覆盖默认情况下创建的ResourceMapping的属性。它的属性用于创建映射并更改映射类上方法的相关返回值。默认情况下,Spring Data Rest会根据存储库定义中使用的对象的类名创建默认值。
答案 2 :(得分:3)
/customerModels
,因为您的默认方法会返回CustomerModel
列表。因此,您可以尝试将此@RestResource(path = "names")
添加到您的方法中,然后将其访问为:
http://localhost:8080/yourapp/people/search/names
。看这里:Spring data docs