ChrisGeo ChrisGeo - 6 months ago 136
Java Question

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?

Answer

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

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

Comments