Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers

jcoig picture jcoig · Sep 11, 2014 · Viewed 9.6k times · Source

Let's say I have two repositories:

@RepositoryRestResource(collectionResourceRel = "person", path = "person")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
    List<Person> findByLastName(@Param("name") String name);
}

and

@RepositoryRestResource(collectionResourceRel = "person1", path = "person1")
public interface PersonRepository1 extends PagingAndSortingRepository<Person1, Long> {
    List<Person1> findByLastName(@Param("name") String name);
}

with one regular controller:

@Controller
public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public HttpEntity<Hello> hello(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
        Hello hello = new Hello(String.format("Hello, %s!", name));
        hello.add(linkTo(methodOn(HelloController.class).hello(name)).withSelfRel());
        return new ResponseEntity<>(hello, HttpStatus.OK);
    }
}

Now, a response for http://localhost:8080/ is:

{
  "_links" : {
    "person" : {
      "href" : "http://localhost:8080/person{?page,size,sort}",
      "templated" : true
    },
    "person1" : {
      "href" : "http://localhost:8080/person1{?page,size,sort}",
      "templated" : true
    }
  }
}

but I want to get something like this:

{
  "_links" : {
    "person" : {
      "href" : "http://localhost:8080/person{?page,size,sort}",
      "templated" : true
    },
    "person1" : {
      "href" : "http://localhost:8080/person1{?page,size,sort}",
      "templated" : true
    },
    "hello" : {
      "href" : "http://localhost:8080/hello?name=World"
    }
  }
}

Answer

palisade picture palisade · Sep 30, 2014
@Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));
        return resource;
    }
}

based on