在Spring REST HATEOAS中使用RepositoryRestResource-s和常规控制器对root请求进行自定义响应

时间:2014-09-11 09:12:23

标签: spring rest spring-boot hateoas spring-hateoas

我们说我有两个存储库:

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

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

使用一个常规控制器:

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

现在,http://localhost:8080/的回复是:

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

但我想得到这样的东西:

{
  "_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"
    }
  }
}

2 个答案:

答案 0 :(得分:29)

@Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {

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

基于

答案 1 :(得分:1)

您需要为注册为Bean的Person资源提供ResourceProcessory。见https://stackoverflow.com/a/24660635/442773