问题
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));
}
}
回答1:
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 (i.e 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
来源:https://stackoverflow.com/questions/58505549/how-does-spring-get-the-result-from-an-endpoint-that-returns-completablefuture-o