0
# Spring Boot WebFlux Starter
1
2
Spring Boot WebFlux Starter provides a comprehensive foundation for building reactive, non-blocking web applications using Spring Framework's reactive web support. It automatically configures Spring WebFlux with Reactor Netty, includes reactive JSON processing, and integrates seamlessly with the reactive ecosystem for building scalable microservices and real-time applications.
3
4
## Package Information
5
6
- **Package Name**: org.springframework.boot:spring-boot-starter-webflux
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your `pom.xml` dependencies:
10
11
```xml
12
<dependency>
13
<groupId>org.springframework.boot</groupId>
14
<artifactId>spring-boot-starter-webflux</artifactId>
15
<version>3.5.3</version>
16
</dependency>
17
```
18
19
For Gradle:
20
21
```gradle
22
implementation 'org.springframework.boot:spring-boot-starter-webflux:3.5.3'
23
```
24
25
## Core Imports
26
27
Spring Boot WebFlux provides two programming models through standard Spring imports:
28
29
```java
30
// Annotation-based controllers
31
import org.springframework.web.bind.annotation.RestController;
32
import org.springframework.web.bind.annotation.GetMapping;
33
import org.springframework.web.bind.annotation.PostMapping;
34
import org.springframework.web.bind.annotation.RequestBody;
35
import org.springframework.web.bind.annotation.PathVariable;
36
37
// Reactive types
38
import reactor.core.publisher.Mono;
39
import reactor.core.publisher.Flux;
40
41
// Functional routing
42
import org.springframework.web.reactive.function.server.RouterFunction;
43
import org.springframework.web.reactive.function.server.RouterFunctions;
44
import org.springframework.web.reactive.function.server.ServerRequest;
45
import org.springframework.web.reactive.function.server.ServerResponse;
46
47
// WebClient for reactive HTTP calls
48
import org.springframework.web.reactive.function.client.WebClient;
49
```
50
51
## Basic Usage
52
53
### Annotated Controller Example
54
55
```java
56
@RestController
57
@RequestMapping("/api/users")
58
public class UserController {
59
60
@GetMapping("/{id}")
61
public Mono<User> getUser(@PathVariable String id) {
62
return userService.findById(id);
63
}
64
65
@GetMapping
66
public Flux<User> getAllUsers() {
67
return userService.findAll();
68
}
69
70
@PostMapping
71
public Mono<User> createUser(@RequestBody Mono<User> user) {
72
return user.flatMap(userService::save);
73
}
74
}
75
```
76
77
### Functional Routing Example
78
79
```java
80
@Configuration
81
public class RouterConfiguration {
82
83
@Bean
84
public RouterFunction<ServerResponse> apiRoutes(UserHandler handler) {
85
return RouterFunctions.route()
86
.GET("/api/users/{id}", handler::getUser)
87
.GET("/api/users", handler::listUsers)
88
.POST("/api/users", handler::createUser)
89
.build();
90
}
91
}
92
```
93
94
### WebClient Example
95
96
```java
97
@Service
98
public class ExternalApiService {
99
100
private final WebClient webClient;
101
102
public ExternalApiService(WebClient.Builder builder) {
103
this.webClient = builder.baseUrl("https://api.example.com").build();
104
}
105
106
public Mono<ApiResponse> fetchData(String id) {
107
return webClient.get()
108
.uri("/data/{id}", id)
109
.retrieve()
110
.bodyToMono(ApiResponse.class);
111
}
112
}
113
```
114
115
## Architecture
116
117
Spring Boot WebFlux Starter brings together several key components:
118
119
- **Reactive Web Framework**: Spring WebFlux with annotation-based and functional programming models
120
- **Embedded Server**: Reactor Netty (default), with support for Tomcat, Jetty, and Undertow
121
- **Reactive Streams**: Built on Project Reactor (Mono/Flux) for non-blocking operations
122
- **HTTP Client**: WebClient for reactive HTTP communication
123
- **JSON Processing**: Jackson integration for reactive JSON serialization/deserialization
124
- **Error Handling**: Reactive exception handlers with customizable error responses
125
- **AutoConfiguration**: Automatic configuration of reactive web components
126
127
## Capabilities
128
129
### Annotation-Based Controllers
130
131
Traditional Spring MVC-style controllers enhanced with reactive return types. Perfect for developers familiar with Spring MVC who want to adopt reactive programming.
132
133
```java { .api }
134
@RestController
135
public class ReactiveController {
136
@GetMapping("/resource/{id}")
137
public Mono<Resource> getResource(@PathVariable String id) { }
138
139
@PostMapping("/resource")
140
public Mono<Resource> createResource(@RequestBody Mono<Resource> resource) { }
141
}
142
```
143
144
[Annotation-Based Controllers](./annotation-controllers.md)
145
146
### Functional Routing
147
148
Modern functional approach using router functions and handler functions. Ideal for building lightweight, composable APIs with explicit request routing.
149
150
```java { .api }
151
public interface RouterFunction<T extends ServerResponse> {
152
Mono<HandlerFunction<T>> route(ServerRequest request);
153
}
154
155
public class RouterFunctions {
156
public static <T extends ServerResponse> RouterFunction<T> route(
157
RequestPredicate predicate,
158
HandlerFunction<T> handlerFunction
159
) { }
160
}
161
```
162
163
[Functional Routing](./functional-routing.md)
164
165
### Reactive HTTP Client
166
167
WebClient provides a modern, reactive HTTP client for making non-blocking HTTP requests with full integration into the reactive ecosystem.
168
169
```java { .api }
170
public interface WebClient {
171
RequestHeadersUriSpec<?> get();
172
RequestBodyUriSpec post();
173
RequestBodyUriSpec put();
174
RequestHeadersUriSpec<?> delete();
175
176
interface Builder {
177
Builder baseUrl(String baseUrl);
178
Builder defaultHeader(String header, String... values);
179
WebClient build();
180
}
181
}
182
```
183
184
[WebClient](./webclient.md)
185
186
### Server Configuration
187
188
Comprehensive server configuration supporting multiple embedded servers with extensive customization options for production deployments.
189
190
```java { .api }
191
public interface ReactiveWebServerFactory {
192
WebServer getWebServer(HttpHandler httpHandler);
193
}
194
195
public interface ConfigurableReactiveWebServerFactory extends ReactiveWebServerFactory {
196
void setPort(int port);
197
void setAddress(InetAddress address);
198
void setSsl(Ssl ssl);
199
}
200
```
201
202
[Server Configuration](./server-configuration.md)
203
204
### Error Handling
205
206
Reactive error handling with customizable exception handlers, providing consistent error responses across different content types.
207
208
```java { .api }
209
public interface ErrorWebExceptionHandler extends WebExceptionHandler {
210
Mono<Void> handle(ServerWebExchange exchange, Throwable ex);
211
}
212
213
public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExceptionHandler {
214
protected abstract RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes);
215
}
216
```
217
218
[Error Handling](./error-handling.md)
219
220
### Configuration Properties
221
222
Comprehensive configuration options through Spring Boot properties for customizing WebFlux behavior, static resources, and server settings.
223
224
```java { .api }
225
@ConfigurationProperties("spring.webflux")
226
public class WebFluxProperties {
227
private String basePath;
228
private String staticPathPattern = "/**";
229
private String webjarsPathPattern = "/webjars/**";
230
private boolean hiddenMethodFilter = true;
231
private final Format format = new Format();
232
private final Problemdetails problemdetails = new Problemdetails();
233
}
234
```
235
236
[Configuration](./configuration.md)
237
238
### Testing Support
239
240
Reactive testing utilities and WebTestClient for comprehensive testing of WebFlux applications with full integration testing capabilities.
241
242
```java { .api }
243
public interface WebTestClient {
244
RequestHeadersUriSpec<?> get();
245
RequestBodyUriSpec post();
246
RequestBodyUriSpec put();
247
RequestBodyUriSpec patch();
248
RequestHeadersUriSpec<?> delete();
249
250
static Builder bindToServer();
251
static Builder bindToController(Object... controllers);
252
static Builder bindToApplicationContext(ApplicationContext applicationContext);
253
static Builder bindToRouterFunction(RouterFunction<?> routerFunction);
254
static Builder bindToWebHandler(WebHandler webHandler);
255
}
256
```
257
258
[Testing](./testing.md)
259
260
## Common Integration Patterns
261
262
### Spring Data Reactive Repositories
263
264
```java
265
@Repository
266
public interface UserRepository extends ReactiveCrudRepository<User, String> {
267
Flux<User> findByStatus(String status);
268
Mono<User> findByEmail(String email);
269
}
270
```
271
272
### Reactive Security Integration
273
274
```java
275
@EnableWebFluxSecurity
276
public class SecurityConfig {
277
278
@Bean
279
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
280
return http
281
.authorizeExchange(exchanges -> exchanges
282
.pathMatchers("/public/**").permitAll()
283
.anyExchange().authenticated()
284
)
285
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt)
286
.build();
287
}
288
}
289
```
290
291
### Server-Sent Events
292
293
```java
294
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
295
public Flux<String> streamEvents() {
296
return Flux.interval(Duration.ofSeconds(1))
297
.map(sequence -> "Event " + sequence);
298
}
299
```