Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
    }
}
like image 626
MA1 Avatar asked Oct 22 '19 13:10

MA1


People also ask

What is completablefuture in Spring Boot?

The CompletableFuture implements Future interface, it can combine multiple asynchronous computations, handle possible errors and offers much more capabilities. Let's get down to writing some code and see the benefits. Create a sample Spring Boot project and add the following dependencies.

What is completablefuture method in JavaScript?

This method waits for the first stage (which applies an uppercase conversion) to complete. Its result is passed to the specified Function, which returns a CompletableFuture, whose result will be the result of the returned CompletableFuture.

How to get REST API endpoints in Spring Boot?

For getting these endpoints, there are three options: an event listener, Spring Boot Actuator, or the Swagger library. 3. Event Listener Approach For creating a REST API service, we use @RestController and @RequestMapping in the controller class.

How to create a completablefuture with a predefined result?

Creating a Completed CompletableFuture The simplest example creates an already completed CompletableFuture with a predefined result. Usually, this may act as the starting stage in your computation. The getNow (null) returns the result if completed (which is obviously the case), but otherwise returns null (the argument). 2.


1 Answers

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

like image 143
Ken Chan Avatar answered Nov 14 '22 23:11

Ken Chan