简体   繁体   中英

How does Spring get the result from an endpoint that returns CompletableFuture object?

In the code below, when the endpoint getPerson gets hit, the response will be a JSON of type Person. How does Spring convert CompletableFuture<Person> to Person ?

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;


    @GetMapping("/persons/{personId}" )
    public CompletableFuture<Person> getPerson(@PathVariable("personId") Integer personId) {

        return CompletableFuture.supplyAsync(() -> personService.getPerson(personId));
    }
}

When the CompletableFuture is returned, it triggers Servlet 3.0 asynchronous processing feature which the execution of the CompletableFuture will be executed in other thread such that the server thread that handle the HTTP request can be free up as quickly as possible to process other HTTP requests. (See a series of blogpost start from this for detailed idea)

The @ResponseBody annotated on the @RestController will cause Spring to convert the controller method 's retuned value (ie Person ) through a HttpMessageConverter registered internally. One of its implementation is MappingJackson2HttpMessageConverter which will further delegate to the Jackson to serialise the Person object to a JSON string and send it back to the HTTP client by writing it to HttpServletResponse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM