Friday, 4 July 2025

What is mono in spring 5

 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

FeatureMonoFlux
Emits0 or 1 item0 to N items
Use caseSingle result (e.g., 1 user)Multiple results (e.g., user list)
BackpressureYesYes

✅ 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

java
@RestController public class UserController { @GetMapping("/user/{id}") public Mono<User> getUserById(@PathVariable String id) { return userService.findById(id); // returns Mono<User> } }

⚙️ Creating a Mono

java
Mono<String> monoJust = Mono.just("Hello"); Mono<Object> monoEmpty = Mono.empty(); Mono<Object> monoError = Mono.error(new RuntimeException("Failed"));

๐Ÿ”„ Chaining with Mono

java
Mono.just("Hello") .map(String::toUpperCase) .flatMap(value -> Mono.just(value + " WORLD")) .subscribe(System.out::println); // prints: HELLO WORLD

๐Ÿงต Benefits of using Mono

  • Non-blocking I/O.

  • Better resource utilization under high concurrency.

  • Scalable and reactive microservice development.


๐Ÿ”š Summary

TermMeaning
MonoA reactive type that emits 0 or 1 element asynchronously
LibraryFrom Project Reactor, used in Spring WebFlux
Typical useSingle 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

webflux-mono-flux/ ├── src/ │ ├── main/ │ │ ├── java/com/example/webflux/ │ │ │ ├── controller/UserController.java │ │ │ ├── model/User.java │ │ │ ├── repository/UserRepository.java │ │ │ ├── service/UserService.java │ │ │ └── WebfluxApplication.java │ │ └── resources/ │ │ └── application.yml └── pom.xml

๐Ÿ“œ Code

1️⃣ User.java – Model

java
package com.example.webflux.model; public class User { private String id; private String name; public User() {} public User(String id, String name) { this.id = id; this.name = name; } // Getters & Setters }

2️⃣ UserRepository.java – Simulated DAO

java
package com.example.webflux.repository; import com.example.webflux.model.User; import org.springframework.stereotype.Repository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @Repository public class UserRepository { private final Map<String, User> userStore = new ConcurrentHashMap<>(); public Flux<User> findAll() { return Flux.fromIterable(userStore.values()); } public Mono<User> findById(String id) { return Mono.justOrEmpty(userStore.get(id)); } public Mono<User> save(User user) { userStore.put(user.getId(), user); return Mono.just(user); } }

3️⃣ UserService.java – Business Logic

java
package com.example.webflux.service; import com.example.webflux.model.User; import com.example.webflux.repository.UserRepository; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service public class UserService { private final UserRepository repository; public UserService(UserRepository repository) { this.repository = repository; } public Flux<User> getAllUsers() { return repository.findAll(); } public Mono<User> getUserById(String id) { return repository.findById(id); } public Mono<User> createUser(User user) { return repository.save(user); } }

4️⃣ UserController.java – WebFlux Controller

java
package com.example.webflux.controller; import com.example.webflux.model.User; import com.example.webflux.service.UserService; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/users") public class UserController { private final UserService service; public UserController(UserService service) { this.service = service; } @GetMapping public Flux<User> getAllUsers() { return service.getAllUsers(); } @GetMapping("/{id}") public Mono<User> getUserById(@PathVariable String id) { return service.getUserById(id); } @PostMapping public Mono<User> createUser(@RequestBody User user) { return service.createUser(user); } }

5️⃣ WebfluxApplication.java

java
package com.example.webflux; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebfluxApplication { public static void main(String[] args) { SpringApplication.run(WebfluxApplication.class, args); } }

6️⃣ application.yml

yaml
server: port: 8080 spring: main: web-application-type: reactive

๐Ÿ”ง pom.xml – Dependencies

xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> </dependencies>

๐Ÿงช Sample API Requests (Postman or curl)

bash
# Create user curl -X POST http://localhost:8080/users -H "Content-Type: application/json" \ -d '{"id": "1", "name": "Swamy"}' # Get all users curl http://localhost:8080/users # Get single user curl http://localhost:8080/users/1