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));
}
}
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With