简体   繁体   中英

Spring Data Rest override controller for Templated Link

I am using Spring Data REST to expose various domain objects as resources.

@Entity
class Person() {
    //fields
}

public interface PersonRepository implemets PagingAndSortingRepository<Person, Long> {

}

So now /persons will be mapped to the repository methods.

Let's say I want to override the GET method. So I do:

@RestController
@RequestMapping("/persons")
public class PersonController {

    private PersonRepository repository;

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<?> getAll(Pageable pageable, PagedResourcesAssembler<Person> assembler) {

        Page<Student> page = repository.findAll();
        return ResponseEntity.ok(assembler.toResource(page));

    }
}

Ok so when I hit http://localhost:8080/persons , as expected it will be handled by the PersonController::getAll method.

It will provide me with this JSON

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/api/persons{?page,size,sort}",
      "templated": true
    }
  },
  "_embedded": {
    "persons": [
      {
        "active": true,
        "email": "mail@mail.com",
        "name": "myname",
        "phoneNumber": "1234-456",
        "surname": "mysurname",
        "userName": "username"
      }
    ]
  },
  "page": {
    "size": 20,
    "totalElements": 1,
    "totalPages": 1,
    "number": 0
  }
}

However, if I click the self link the response will NOT be handled from my custom controller but from the original @RepositoryRestController of SDR .

Is there a way I can configure the custom controller to also include handle templated hrefs?

http://localhost:8080/persons vs http://localhost:8080/api/persons

add /api to your controller requestmapping to overwrite the SDR controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM