Spring WebFlux Controller

Learn how to create and execute a Spring WebFlux Controller.

We'll cover the following...

Now that we’ve taken an initial tour through a bare Spring Boot project, we can code our first controller.

Creating a Spring WebFlux controller

Let’s start by reviewing the ServerController class that we created:

package com.greglturnquist.hackingspringboot.reactive;
import reactor.core.publisher.Flux;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //1
public class ServerController {
private final KitchenService kitchen; //2
public ServerController(KitchenService kitchen) {
this.kitchen = kitchen;
}
@GetMapping(value = "/server", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<Dish> serveDishes() { //3
return this.kitchen.getDishes();
}
}
ServerController class

Let’s see what the ServerController code we’ve written above is doing:

  • In line 7, @RestController is a Spring web annotation that marks this class as a controller without using any templating. Instead, it responds to web calls by serializing results and writing them straight into the HTTP response body.

  • In line 10, KitchenService (which we’ll write shortly) is provided to this controller via constructor injection. Spring seeks an instance of this service when the application starts automatically feeding it to the constructor.

  • In line 15, @GetMapping(...) is another Spring web annotation that routes HTTP GET /server calls to the serveDishes() method. . The media type it serves is text/event-stream, a stream of text that clients can easily consume, which we’ll see further down.

The Flux<Dish> object is just like what we saw earlier, a type that returns a collection of prepared meals. The ...