In Spring 5, Mono is part of the Project Reactor library and is a reactive programming abstraction introduced to support Reactive Streams — a specification for asynchronous, non-blocking stream processing with backpressure.
๐ง What is Mono?
Mono<T> is a reactive publisher that emits at most one item:
-
Zero or one element.
-
Optionally followed by a completion or error signal.
It represents asynchronous computation that eventually completes with:
-
A single value (like
Optional<T>), -
No value, or
-
An error.
๐ Mono vs Flux
| Feature | Mono | Flux |
|---|---|---|
| Emits | 0 or 1 item | 0 to N items |
| Use case | Single result (e.g., 1 user) | Multiple results (e.g., user list) |
| Backpressure | Yes | Yes |
✅ When to use Mono in Spring?
You use Mono:
-
In Spring WebFlux (reactive web framework) as return types in controller methods.
-
When your logic returns only one value asynchronously, e.g., database record, API call result.
๐งช Example: Mono in a Spring WebFlux Controller
⚙️ Creating a Mono
๐ Chaining with Mono
๐งต Benefits of using Mono
-
Non-blocking I/O.
-
Better resource utilization under high concurrency.
-
Scalable and reactive microservice development.
๐ Summary
| Term | Meaning |
|---|---|
Mono | A reactive type that emits 0 or 1 element asynchronously |
| Library | From Project Reactor, used in Spring WebFlux |
| Typical use | Single database call, REST API call, or service response |
Here's a complete Spring Boot WebFlux project example using both Mono and Flux. This app simulates a simple User Service that allows:
-
Retrieving all users (
Flux) -
Retrieving a user by ID (
Mono) -
Creating a new user (
Mono)
๐ Project Structure
๐ Code
1️⃣ User.java – Model
2️⃣ UserRepository.java – Simulated DAO
3️⃣ UserService.java – Business Logic
4️⃣ UserController.java – WebFlux Controller
5️⃣ WebfluxApplication.java
6️⃣ application.yml
๐ง pom.xml – Dependencies
๐งช Sample API Requests (Postman or curl)
No comments:
Post a Comment