Reactive Programming : Spring

Reading Time: 3 minutes

Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming involves modeling data and events as observable data streams and implementing data processing routines to react to the changes in those streams.

In the reactive style of programming, we make a request for the resource and start performing other things. When the data is available, we get the notification along with data in the form of call back function. In the callback function, we handle the response as per application/user needs.

Now the question comes, how we can make the Java applications in a reactive way. And the answer is using Spring Webflux.

Spring Webflux:

Spring Webflux is a reactive-stack web framework which is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers. It was added in Spring 5.0.

Spring Webflux uses project reactor as a reactive library. Reactor is a Reactive Streams library and, therefore, all of its operators support non-blocking back pressure.

Spring Webflux uses 2 Publishers:

  • Mono
  • Flux



A Mono is a specialized Publisher that emits at most one item and then optionally terminates with an onComplete signal or an onError signal. In short, it returns 0 or 1 element.

Mono noData = Mono.empty();

Mono data = Mono.just(“rishi”);



A Flux is a standard Publisher representing an asynchronous sequence of 0 to N emitted items, optionally terminated by either a completion signal or an error. These 3 types of signal translate to calls to a downstream subscriber’s onNext, onComplete or onError methods.

Flux flux1 = Flux.just(“Ice”, “cream”, “Icecream”);

Flux flux2 = Flux.fromIterable(Arrays.asList(“A”, “B”, “C”));

Flux flux3 = Flux.range(5, 3);

// subscribe


To subscribe, we need to call the subscribe method on Flux. There are different variants of subscribe methods available which we need to use as per the need:

So now, we are familiar with Mono and Flux so let’s proceed with how to create a reactive application with Spring Web Flux.

First of all, we need to add the following in pom.xml:


Then, we need to define the main class as follows:

public class MainApplication {
    public static void main(String[] args) {, args);

and then, we need to define the classes for rest APIs. Spring WebFlux comes in two flavors: functional and annotation-based.


public class UserRestController {
  private UserRepository userRepository;
    public Flux getUsers() {
        return userRepository.findAll();
    public Mono getUserById(@PathVariable String id) {
        return userRepository.findById(id);
    public Mono addUser(@RequestBody User user) {


In the functional variant, we keep the routing configuration separate from the actual handling of the requests.

We have defined UserRouter for defining routes and UserHandler to handle the request.


public class UserRouter {
    public RouterFunction userRoutes(UserHandler userHandler) {
        return RouterFunctions
                .route(RequestPredicates.POST("/users").and(accept(MediaType.APPLICATION_JSON)), userHandler::addUser)
                .andRoute(RequestPredicates.GET("/users").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUsers)
                .andRoute(RequestPredicates.GET("/users/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUserById);


public class UserHandler {
    private UserRepository userRepository;
    public Mono addUser(ServerRequest request) {
        Mono userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromPublisher(userMono.flatMap(userRepository::save), User.class));
    public Mono getUsers(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userRepository.findAll(), User.class)
public Mono getUserById(ServerRequest request) {
        String id = request.pathVariable("id");
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userRepository.findById(id), User.class)

Run application:

mvn spring-boot:run

By default, it runs on 8080 port, so you can access your URL at http://localhost:8080


Written by 

Deepak kumar is a Software Intern at Knoldus Inc. He has done Post Graduation from Ajay Kumar Garg Engineering College Ghaziabad. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is a quick learner, problem solver and always enjoy to help others. His hobbies playing Cricket and watching Hollywood movies.