如何使用WebClient使用Spring Hateoas CollectionModel



我想好了如何使用EntityModel,但到目前为止还无法使用CollectionModel(Spring代码使用Groovy(

我的班级:

@Relation(value = "person", collectionRelation = "people")
class Person {
long id
String firstName
String lastName
}

我的控制器:

CollectionModel<Person> getPeople() {
Person person = new Person(
id: 2L,
firstName: 'Mark',
lastName: 'Hamil'
)
Collection<Person> people = Collections.singleton(person)
CollectionModel.of(people)
}

然后我创建了一个服务来消耗控制器的输出:

CollectionModel<Person> model= this.webClient.get().uri('localhost:8080/api/people')
.retrieve()
.bodyToMono(new TypeReferences.CollectionModelType<Person>())
.block()
List<Person> people = model.content

但模型是空白的。我不确定我做错了什么。

以下是localhost:8080/api/people 的原始输出

{
"_embedded": {
"people": [
{
"id": 2,
"firstName": "Mark",
"lastName": "Hamil"
}
]
}

}

在https://gitter.im/spring-projects/spring-hateoas#并且获得了一些见解,我能够使这项工作发挥作用。请注意,这是在使用Groovy。

首先,在控制器中,我确保产品设置为hal:

@RequestMapping(method = RequestMethod.GET, produces = "application/hal+json")
CollectionModel<Person> getPeople() {
Link link = linkTo(PersonController).withSelfRel()
List<EntityModel> entityModelList = [this.getPerson()]
}

其中this.getPerson()为:

EntityModel<Person> getPerson() {
Person person = new Person(
id: 2L,
firstName: 'Mark',
lastName: 'Hamil'
)
Link link = linkTo(PersonController).slash(person.id).withSelfRel()
EntityModel<Person> personEntityModel = EntityModel.of(person, link)
personEntityModel
}

然后在调用api中:

Mono<CollectionModel<EntityModel<Person>>> personCollectionModel = this.webClient
.get()
.uri('localhost:8080/uswf-api/people')
.accept(MediaTypes.HAL_JSON)
.exchange()
.flatMap { response ->
if (response.statusCode().isError()) {
System.out.println('Error')
} else {
response.bodyToMono(new ParameterizedTypeReference<CollectionModel<EntityModel<Person>>>() {})
}
}

然后我可以通过订阅结果来使用这个结果:

personCollectionModel.subscribe( { collectionModel -> collectionModel.content })

最新更新