Spring / Spring Boot 4 Basics Interview Questions
What is Spring WebFlux and reactive programming in Spring Boot 4?
Spring WebFlux is Spring's reactive web framework, built on Project Reactor. It is an alternative to Spring MVC for building non-blocking, asynchronous web applications. Spring Boot 4 supports both Spring MVC (servlet-based) and WebFlux (reactive) in the same framework.
| Aspect | Spring MVC | Spring WebFlux |
|---|---|---|
| Programming model | Imperative / blocking | Reactive / non-blocking |
| Thread model | One thread per request (or virtual threads) | Event loop; fewer threads handle more connections |
| Return types | Object, ResponseEntity | Mono |
| Persistence | Spring Data JPA (blocking) | Spring Data R2DBC (reactive) |
| Best for | Traditional CRUD, simple blocking I/O | High concurrency, streaming, SSE, WebSocket |
// WebFlux reactive controller: @RestController @RequestMapping("/api/orders") public class OrderReactiveController { private final OrderReactiveService service; // Mono<T>: 0 or 1 item (like Optional) @GetMapping("/{id}") public Mono<ResponseEntity<OrderDto>> getOrder(@PathVariable String id) { return service.findById(id) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.notFound().build()); } // Flux<T>: 0 to N items (like Stream) @GetMapping public Flux<OrderDto> listOrders() { return service.findAll(); } // Server-Sent Events (SSE) streaming: @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<OrderDto> streamOrders() { return service.streamNewOrders() // infinite stream of new orders .delayElements(Duration.ofSeconds(1)); } // R2DBC (reactive database): // Replace JpaRepository with ReactiveCrudRepository } // Starter for WebFlux: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> // WebFlux native API versioning (Boot 4): @GetMapping(path = "/{id}", version = "2.0") public Mono<OrderDtoV2> getOrderV2(@PathVariable String id) { return service.findByIdV2(id); }
More Related questions...