gpt4 book ai didi

spring - 带有 RepositoryRestResource-s 和常规 Controller 的 Spring REST HATEOAS 中的根请求的自定义响应

转载 作者:IT老高 更新时间:2023-10-28 13:46:29 27 4
gpt4 key购买 nike

假设我有两个存储库:

@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 :

@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"
}
}
}

最佳答案

@Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {

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

基于

关于spring - 带有 RepositoryRestResource-s 和常规 Controller 的 Spring REST HATEOAS 中的根请求的自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25783487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com