带有 RepositoryRestResource-s 和常规控制器的 Spring REST HATEOAS 中的根请求的自定义响应
Posted
技术标签:
【中文标题】带有 RepositoryRestResource-s 和常规控制器的 Spring REST HATEOAS 中的根请求的自定义响应【英文标题】:Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers 【发布时间】:2014-11-05 04:03:12 【问题描述】:假设我有两个存储库:
@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"
【问题讨论】:
【参考方案1】:@Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource>
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource)
resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));
return resource;
基于
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output How to add links to root resource in Spring Data REST?【讨论】:
【参考方案2】:您需要为您的 Person 资源注册为 Bean 的 ResourceProcessory。见https://***.com/a/24660635/442773
【讨论】:
但我不想更改任何http://localhost:8080/person
、http://localhost:8080/person1
或http://localhost:8080/hello
请求的响应。我想更改 http://localhost:8080/
请求的自动生成响应。以上是关于带有 RepositoryRestResource-s 和常规控制器的 Spring REST HATEOAS 中的根请求的自定义响应的主要内容,如果未能解决你的问题,请参考以下文章
spring Restcontroller 或 RepositoryRestResource 用啥
仅当存在特定标头时才响应 Spring RepositoryRestResource
删除 Spring RepositoryRestResource 中的“_embedded”属性
如何测试 Spring Data Rest @RepositoryRestResource?