DEV Community

realNameHidden
realNameHidden

Posted on

Mono in Spring Boot Explained with Simple Examples

๐ŸŸข Imagine this scenario:
Normally, in Spring Boot (MVC), when you write:


@GetMapping("/hello")
public String sayHello() {
    return "Hello World!";
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Here, the method returns a String directly.

The request โ†’ executes the method โ†’ response is returned immediately.

๐ŸŸก Now, what if the response will come later?

Sometimes data doesnโ€™t come instantly (e.g., fetching from DB, calling another API, adding a delay).
Instead of blocking the thread, we want to return a โ€œpromiseโ€ that will complete later.

Thatโ€™s where Mono comes in.
Think of Mono as a box that will contain ONE value in the future.

๐Ÿ”น Example 1: Basic Mono

@GetMapping("/hello")
public Mono<String> sayHello() {
    return Mono.just("Hello Reactive World!");
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Here:

Mono.just("Hello Reactive World!") means:
"I promise I will give you this string โ€” just not necessarily right now."
When the browser calls /hello, Spring WebFlux unwraps the Mono and sends the string.

๐Ÿ”น Example 2: Mono with Delay


@GetMapping("/delayed")
public Mono<String> delayedHello() {
    return Mono.just("Hello after delay!")
               .delayElement(Duration.ofSeconds(2)); // respond after 2 seconds
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Here:

The response comes after 2 seconds, but the server doesnโ€™t block the thread during the wait.
That means the server can serve other requests meanwhile.
๐Ÿ”น Example 3: Mono with an Object

record User(String id, String name) {}
@GetMapping("/user")
public Mono<User> getUser() {
    User user = new User("101", "Alice");
    return Mono.just(user);
}

Enter fullscreen mode Exit fullscreen mode

}
๐Ÿ‘‰ Browser Response:

{
  "id": "101",
  "name": "Alice"
}

Enter fullscreen mode Exit fullscreen mode

}
๐ŸŸข Very Simple Analogy

Think of Mono as:

A parcel delivery service ๐Ÿ“ฆ
You place an order โ†’ you get a tracking ID immediately (Mono).
The actual parcel (data) may come later.
When it arrives, you open it and see the item.
So, Mono = โ€œa container for ONE thing that comes now or later.โ€

โœ… Use Mono when:

Your API returns a single item asynchronously.
You want non-blocking performance in Spring WebFlux.

Top comments (0)