Backend Development 12 min read

Mastering Spring WebFlux: Reactive Programming in Spring Boot 3

An in‑depth guide to Spring WebFlux explains its reactive, non‑blocking architecture, core Mono and Flux APIs, annotation‑based and functional programming models, Maven setup, code examples, and why developers should consider learning this modern backend framework for Spring Boot 3.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Spring WebFlux: Reactive Programming in Spring Boot 3

Environment: Spring Boot 3.0.5

1. What is WebFlux

Spring Web MVC was originally designed for the Servlet API and containers. In version 5.0, Spring introduced the reactive stack WebFlux, which is fully non‑blocking, supports reactive streams back‑pressure, and can run on servers such as Netty, Undertow, or any Servlet 3.1+ container. Its core is built on the Reactor API.

2. Why WebFlux

One reason is the need for a non‑blocking network stack that handles concurrency with few threads and scales using fewer hardware resources. Although Servlet 3.1 provides a non‑blocking I/O API, using it diverges from other parts of the Servlet API, so a new generic API is required for any non‑blocking runtime. Another reason is functional programming: Java 8 lambda expressions enable functional APIs, which benefit asynchronous, non‑blocking applications and align with Reactive Streams concepts, allowing Spring WebFlux to expose functional web endpoints alongside annotation controllers.

3. What is "reactive"

The term refers to a programming model built around reacting to changes, such as network components reacting to I/O events or UI controllers reacting to mouse events. In this sense, non‑blocking code is reactive because actions occur only when data becomes available. Reactive programming is closely tied to back‑pressure: in synchronous code, blocking calls naturally apply back‑pressure, while in non‑blocking code the speed of event production must be controlled so fast producers do not overwhelm consumers.

Reactive Streams is a specification (adopted by Java 9) that defines the interaction between asynchronous components and back‑pressure. For example, a data repository (publisher) can emit data that an HTTP server (subscriber) writes to the response, allowing the subscriber to control the rate of data emission.

4. Reactive Core API

Reactor is the preferred reactive library for Spring WebFlux. It provides two main types:

Mono : represents 0..1 asynchronous elements.

Flux : represents 0..N asynchronous elements.

Both types support a rich set of operators consistent with the ReactiveX vocabulary and fully implement back‑pressure.

Mono

Mono represents an asynchronous computation that can emit at most one result. In the Reactive Streams spec, a Mono is a Publisher that emits zero or one element.

<code>public static void main(String[] args) {
  // No action is performed when only creating the Mono
  Mono.just(10);
  // The operation runs only after subscription
  Mono.just(10).subscribe(System.out::println);
}</code>

Flux

Flux represents an asynchronous sequence that can emit zero to many elements.

<code>Flux.just(6, 8, 10, 12).map(i -> {
  int res = i * i;
  try {
    TimeUnit.SECONDS.sleep(10);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  return res;
});</code>

Like Mono, the operators are executed only after a subscribe call.

5. Programming Model

The spring-web module contains the reactive foundation for Spring WebFlux, including HTTP abstractions, reactive stream adapters, codecs, and a core WebHandler API with a non‑blocking contract.

WebFlux offers two programming models:

Annotation‑based : Mirrors Spring MVC with the same annotations. Controllers can return reactive types (Mono, Flux) and support reactive @RequestBody parameters.

Functional endpoints : A lightweight, lambda‑based model where routing and handling are defined via beans returning RouterFunction&lt;ServerResponse&gt; .

6. Application Example

Environment Configuration

<code>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
  &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;
&lt;/dependency&gt;</code>

Note: Do not include spring-boot-starter-web , otherwise the Servlet stack will be used by default.

Annotation‑based Controller

<code>@RestController
@RequestMapping("/demos")
public class DemoController {
  private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

  @GetMapping("/index")
  public Mono&lt;String&gt; index() {
    logger.info("start {}, {}", Thread.currentThread().getName(), System.currentTimeMillis());
    Mono&lt;String&gt; result = Mono.just(666);
    logger.info("end {}, {}", Thread.currentThread().getName(), System.currentTimeMillis());
    return result;
  }
}</code>

Functional Router

<code>@Bean
public RouterFunction&lt;ServerResponse&gt; router1() {
  return RouterFunctions.route()
    .GET("/r1", request -> {
      String id = request.queryParam("id").orElse(null);
      if ("2".equals(id)) {
        throw new RuntimeException("Router Param id Error...");
      }
      return ServerResponse.ok().bodyValue("你输入的是id = " + id);
    })
    .build();
}</code>

In WebFlux.fn, an HTTP request is handled by a HandlerFunction that receives a ServerRequest and returns a delayed ServerResponse (i.e., Mono&lt;ServerResponse&gt; ). Both request and response objects are immutable.

Supported Reactive Middleware

Databases: H2, MariaDB, Microsoft SQL Server, MySQL, jasync‑sql MySQL, Postgres, Oracle.

Non‑relational: Redis, MongoDB, Elasticsearch, etc.

7. Should You Learn WebFlux?

WebFlux is a modern, reactive‑oriented web framework that, together with Spring Boot, provides a complete production‑grade solution. Although its adoption may currently be limited, it offers distinct advantages such as asynchronous, non‑blocking programming and excellent performance.

Learning WebFlux equips developers with a new programming model and tools, deepens understanding of reactive programming and the Reactive Streams specification, and can improve performance and scalability in future projects.

However, adopting any new technology requires time and effort. Decide based on your current needs and career goals: if you are interested in reactive programming and anticipate its relevance, investing in WebFlux is worthwhile.

End of article.

JavaSpringReactiveWebFlux
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.