在 Spring Framework 5.0: Functional Web Framework 如何将新创建的实体 ID 放入 webflux 服务器响应中 header

in Spring Framework 5.0: Functional Web Framework how to put the newley created entity's id in webflux serverresponse header

 public Mono<ServerResponse> post(ServerRequest request) {
   final Mono<Person> person = request.bodyToMono(Person.class);
   final String id = ????; //replace this with newly inserted //objects id
   return created(UriComponentsBuilder.fromPath("people/" + 
   id).build().toUri())
        .contentType(APPLICATION_JSON)
        .body(
                fromPublisher(
                        person.map(p -> new Person(p, 
       id)).flatMap(personManager::save), Person.class));
 }

我在这里尝试 post 创建一个实体到服务器。我需要将新创建的 object 的 ID 插入响应的 header 位置。

按照我在 kotlin 中的项目,您可以编写如下代码:

   @Configuration
    class ResumeRoute {

        @Bean
        fun resumeRoutes(@Value("${baseServer:http://localhost:8080}") baseServer: String, resumeRepository: ResumeRepository) = router {

        POST("/resume")
        {


   it.principal().flatMap {
            resumeRepository.save(Resume.emptyResume(UUID.randomUUID().toString(), it.name, Language.EN)).toMono()
        }.flatMap { created(URI("${baseServer}/resume/${it.id}")).build() }
    }

}

}

即使这是 kotlin 而不是 java 版本,这里重要的是你应该先拥有你的实体以获取 id,然后使用它来创建服务器响应

因此您的代码应该如下所示:

public Mono<ServerResponse> post(ServerRequest request) {
    return request.bodyToMono(Person.class)
            .map(personManager::save)
            .flatMap(savedPerson ->
                    created((UriComponentsBuilder.fromPath("people/" + savedPerson.getId()).build().toUri()))
                            .body(fromObject(savedPerson)));
}

希望对您有所帮助