Spring Boot Spring Boot WebFlux and Reactive Programming 2 — Questions and Answers
Question 1: In Spring WebFlux, what is the role of the `ServerRequest` object in a `HandlerFunction`?
- It represents the reactive data source
- It encapsulates the HTTP request including headers, body, and path variables (Correct answer)
- It is used to configure route predicates
- It wraps the underlying Netty channel
Correct answer: It encapsulates the HTTP request including headers, body, and path variables
`ServerRequest` provides access to the HTTP method, URI, headers, and body of an incoming request inside a `HandlerFunction`.
Question 2: Which operator would you use on a `Flux` to transform each element asynchronously using another reactive publisher?
- map
- filter
- flatMap (Correct answer)
- reduce
Correct answer: flatMap
`flatMap` maps each element to a `Publisher` and merges the results, making it ideal for asynchronous transformations in reactive pipelines.
Question 3: How do you enable reactive repository support for MongoDB in Spring Boot?
- Add spring-boot-starter-data-mongodb-reactive (Correct answer)
- Add spring-boot-starter-mongodb and set reactive=true
- Annotate the main class with @EnableReactiveMongo
- Use MongoTemplate with async=true in application.properties
Correct answer: Add spring-boot-starter-data-mongodb-reactive
Adding `spring-boot-starter-data-mongodb-reactive` pulls in the reactive MongoDB driver and auto-configures `ReactiveMongoTemplate` and reactive repositories.
Question 4: What is backpressure in the context of reactive streams?
- A mechanism to pause and resume the event loop
- A signal from subscriber to publisher to slow down data emission (Correct answer)
- A cache strategy to buffer reactive events
- A retry policy for failed reactive sequences
Correct answer: A signal from subscriber to publisher to slow down data emission
Backpressure is the ability of a subscriber to signal upstream publishers to reduce the rate of data emission, preventing out-of-memory errors.
Question 5: Which WebFlux annotation marks a class as a reactive REST controller that returns reactive types?
- @RestController (Correct answer)
- @ReactiveController
- @WebFluxController
- @NonBlockingController
Correct answer: @RestController
`@RestController` works in both Spring MVC and Spring WebFlux; when return types are `Mono` or `Flux`, Spring WebFlux handles them reactively.
Question 6: What property in `application.properties` switches the Spring Boot web application type to reactive?
- spring.web.type=reactive
- spring.main.web-application-type=reactive (Correct answer)
- spring.boot.reactive=true
- server.reactive.enabled=true
Correct answer: spring.main.web-application-type=reactive
Setting `spring.main.web-application-type=reactive` forces Spring Boot to start a reactive web environment using WebFlux instead of the servlet stack.
In Spring WebFlux, what is the role of the `ServerRequest` object in a `HandlerFunction`?