使用RepositoryRestResource-s和常规控制器对Spring REST HATEOAS中的根请求进行自定义响应
假设我有两个存储库:使用RepositoryRestResource-s和常规控制器对Spring REST HATEOAS中的根请求进行自定义响应,spring,rest,spring-boot,hateoas,spring-hateoas,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 = "person", path = "person")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(@Param("name") String name);
}
但我想得到这样的东西:
{
"_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"
}
}
}
您需要为您的Person资源注册一个ResourceProcessory作为Bean。请参见组件 公共类HelloResourceProcessor实现ResourceProcessor{ @凌驾 公共RepositoryLinksResource进程(RepositoryLinksResource资源){ add(ControllerLinkBuilder.linkTo(HelloController.class).withRel(“hello”); 返回资源; } } 基于
http://localhost:8080/person
,http://localhost:8080/person1
或http://localhost:8080/hello
请求。我想更改http://localhost:8080/
请求。
@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);
}
}
{
"_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"
}
}
}
@Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));
return resource;
}
}