Using RepositoryRestResource annotation to change RESTful endpoint not working

2022-09-03 02:15:19

I am new to Spring boot. I was trying to create RESTful web service which also plugs into MongoDB. Everything works fine as the guide explains except for this.

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

}

Here I am trying to change the RESTful endpoint for the repository from the default to . But when I run this, I get 404 if I try but works fine for . In a broader sense how does work? What am I doing wrong here?/customerModels/people/people/customerModels@RepositoryRestResource


答案 1

You can't use slash inside the attribute, but you can set base path in application.properties:path

# 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

Without seeing your entire configuration it is hard to know exactly what is going on in your situation. However using the latest guide at https://github.com/spring-guides/gs-accessing-data-mongodb.git I am able to get it working by making the following changes:

  • 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.

Using this when I run the application I am able to access the repository at http://localhost:8080/people. If I remove the annotation then the CustomerRepository is accessed at http://localhost:8080/customers. Let me know if you want me to post a fork on GitHub.

To answer your question about what RepositoryRestResource is that it overrides the attributes for the ResourceMapping that is created by default. It's attributes are used in creating the mapping and change the related return values of the methods on the mapping class. By default Spring Data Rest creates defaults based on the class names of the objects used in the repository definition.