or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdfunctional-programming.mdhttp-client.mdindex.mdrequest-processing.mdview-resolution.mdwebsocket.md

configuration.mddocs/

0

# Configuration and Setup

1

2

Spring WebFlux provides comprehensive configuration options for setting up reactive web applications, including CORS configuration, resource handling, view resolvers, and custom components integration.

3

4

## Capabilities

5

6

### WebFlux Configurer

7

8

Main callback interface for customizing WebFlux configuration in your application.

9

10

```java { .api }

11

interface WebFluxConfigurer {

12

/**

13

* Configure HTTP message codecs for reading and writing request/response body.

14

* @param configurer the configurer to customize codecs

15

*/

16

default void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {}

17

18

/**

19

* Add custom formatters and converters.

20

* @param registry the formatter registry

21

*/

22

default void addFormatters(FormatterRegistry registry) {}

23

24

/**

25

* Provide a custom Validator instance.

26

* @return the validator to use, or null for default

27

*/

28

default Validator getValidator() { return null; }

29

30

/**

31

* Provide a custom MessageCodesResolver for building message codes.

32

* @return the message codes resolver, or null for default

33

*/

34

default MessageCodesResolver getMessageCodesResolver() { return null; }

35

36

/**

37

* Configure CORS mappings.

38

* @param registry the CORS registry

39

*/

40

default void addCorsMappings(CorsRegistry registry) {}

41

42

/**

43

* Configure path matching options.

44

* @param configurer the path match configurer

45

*/

46

default void configurePathMatching(PathMatchConfigurer configurer) {}

47

48

/**

49

* Configure content type resolution.

50

* @param builder the content type resolver builder

51

*/

52

default void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) {}

53

54

/**

55

* Configure argument resolvers for handler method arguments.

56

* @param configurer the argument resolver configurer

57

*/

58

default void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {}

59

60

/**

61

* Add static resource handlers for serving static content.

62

* @param registry the resource handler registry

63

*/

64

default void addResourceHandlers(ResourceHandlerRegistry registry) {}

65

66

/**

67

* Configure view resolvers for rendering responses.

68

* @param registry the view resolver registry

69

*/

70

default void configureViewResolvers(ViewResolverRegistry registry) {}

71

72

/**

73

* Configure the WebSocket service.

74

* @param service the WebSocket service

75

*/

76

default void configureWebSocketService(WebSocketService service) {}

77

78

/**

79

* Configure blocking execution for @Controller methods.

80

* @param configurer the blocking execution configurer

81

*/

82

default void configureBlockingExecution(BlockingExecutionConfigurer configurer) {}

83

}

84

```

85

86

**Usage Examples:**

87

88

```java

89

@Configuration

90

@EnableWebFlux

91

public class WebFluxConfig implements WebFluxConfigurer {

92

93

@Override

94

public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {

95

// Increase max memory size for JSON parsing

96

configurer.defaultCodecs().maxInMemorySize(1024 * 1024); // 1MB

97

98

// Add custom codec

99

configurer.customCodecs().register(new CustomMessageCodec());

100

}

101

102

@Override

103

public void addCorsMappings(CorsRegistry registry) {

104

registry.addMapping("/api/**")

105

.allowedOrigins("http://localhost:3000", "https://example.com")

106

.allowedMethods("GET", "POST", "PUT", "DELETE")

107

.allowedHeaders("*")

108

.allowCredentials(true)

109

.maxAge(3600);

110

}

111

112

@Override

113

public void addResourceHandlers(ResourceHandlerRegistry registry) {

114

registry.addResourceHandler("/static/**")

115

.addResourceLocations("classpath:/static/")

116

.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)));

117

}

118

119

@Override

120

public void configureViewResolvers(ViewResolverRegistry registry) {

121

registry.freeMarker().prefix("/templates/").suffix(".ftl");

122

registry.defaultViews(new MustacheView());

123

}

124

}

125

```

126

127

### Enable WebFlux Annotation

128

129

Annotation for enabling Spring WebFlux configuration in your application.

130

131

```java { .api }

132

@Target(ElementType.TYPE)

133

@Retention(RetentionPolicy.RUNTIME)

134

@Documented

135

@Import(DelegatingWebFluxConfiguration.class)

136

@interface EnableWebFlux {

137

// Marker annotation with no attributes

138

}

139

```

140

141

**Usage Examples:**

142

143

```java

144

@Configuration

145

@EnableWebFlux

146

public class WebFluxConfig {

147

// Configuration beans

148

}

149

150

// Or on main application class

151

@SpringBootApplication

152

@EnableWebFlux

153

public class MyWebFluxApplication {

154

public static void main(String[] args) {

155

SpringApplication.run(MyWebFluxApplication.class, args);

156

}

157

}

158

```

159

160

### Configuration Support Classes

161

162

Base classes and delegation mechanism for WebFlux configuration.

163

164

```java { .api }

165

class WebFluxConfigurationSupport {

166

/**

167

* Configure request mapping handler mapping.

168

* @return the handler mapping bean

169

*/

170

@Bean

171

RequestMappingHandlerMapping requestMappingHandlerMapping();

172

173

/**

174

* Configure request mapping handler adapter.

175

* @return the handler adapter bean

176

*/

177

@Bean

178

RequestMappingHandlerAdapter requestMappingHandlerAdapter();

179

180

/**

181

* Configure response entity result handler.

182

* @return the result handler bean

183

*/

184

@Bean

185

ResponseEntityResultHandler responseEntityResultHandler();

186

187

/**

188

* Configure response body result handler.

189

* @return the result handler bean

190

*/

191

@Bean

192

ResponseBodyResultHandler responseBodyResultHandler();

193

}

194

195

class DelegatingWebFluxConfiguration extends WebFluxConfigurationSupport {

196

/**

197

* Set the list of configurers to delegate to.

198

* @param configurers the list of WebFluxConfigurer instances

199

*/

200

void setConfigurers(List<WebFluxConfigurer> configurers);

201

}

202

```

203

204

### CORS Configuration

205

206

Registry and registration classes for configuring Cross-Origin Resource Sharing (CORS).

207

208

```java { .api }

209

class CorsRegistry {

210

/**

211

* Add CORS mapping for the specified path pattern.

212

* @param pathPattern the path pattern to match

213

* @return the CORS registration for further configuration

214

*/

215

CorsRegistration addMapping(String pathPattern);

216

}

217

218

class CorsRegistration {

219

/**

220

* Set the allowed origins for cross-origin requests.

221

* @param origins the allowed origins

222

* @return this registration for method chaining

223

*/

224

CorsRegistration allowedOrigins(String... origins);

225

226

/**

227

* Set the allowed origin patterns for cross-origin requests.

228

* @param originPatterns the allowed origin patterns

229

* @return this registration for method chaining

230

*/

231

CorsRegistration allowedOriginPatterns(String... originPatterns);

232

233

/**

234

* Set the HTTP methods to allow.

235

* @param methods the allowed HTTP methods

236

* @return this registration for method chaining

237

*/

238

CorsRegistration allowedMethods(String... methods);

239

240

/**

241

* Set the allowed headers for cross-origin requests.

242

* @param headers the allowed headers

243

* @return this registration for method chaining

244

*/

245

CorsRegistration allowedHeaders(String... headers);

246

247

/**

248

* Set the headers that are exposed to the client.

249

* @param headers the headers to expose

250

* @return this registration for method chaining

251

*/

252

CorsRegistration exposedHeaders(String... headers);

253

254

/**

255

* Set whether credentials are allowed.

256

* @param allowCredentials true to allow credentials

257

* @return this registration for method chaining

258

*/

259

CorsRegistration allowCredentials(boolean allowCredentials);

260

261

/**

262

* Set how long the browser should cache the preflight response.

263

* @param maxAge the cache duration in seconds

264

* @return this registration for method chaining

265

*/

266

CorsRegistration maxAge(long maxAge);

267

}

268

```

269

270

**Usage Examples:**

271

272

```java

273

@Override

274

public void addCorsMappings(CorsRegistry registry) {

275

// Allow all origins for public API

276

registry.addMapping("/api/public/**")

277

.allowedOrigins("*")

278

.allowedMethods("GET", "POST")

279

.allowedHeaders("Content-Type", "Authorization");

280

281

// Restricted CORS for admin API

282

registry.addMapping("/api/admin/**")

283

.allowedOriginPatterns("https://*.mydomain.com")

284

.allowedMethods("GET", "POST", "PUT", "DELETE")

285

.allowedHeaders("*")

286

.allowCredentials(true)

287

.maxAge(3600);

288

289

// WebSocket endpoints

290

registry.addMapping("/websocket/**")

291

.allowedOrigins("http://localhost:3000")

292

.allowCredentials(true);

293

}

294

```

295

296

### Resource Handler Configuration

297

298

Registry and registration classes for configuring static resource serving.

299

300

```java { .api }

301

class ResourceHandlerRegistry {

302

/**

303

* Add a resource handler for serving static resources.

304

* @param pathPatterns the path patterns to match

305

* @return the resource handler registration

306

*/

307

ResourceHandlerRegistration addResourceHandler(String... pathPatterns);

308

}

309

310

class ResourceHandlerRegistration {

311

/**

312

* Add resource locations from which to serve static content.

313

* @param resourceLocations the resource locations

314

* @return this registration for method chaining

315

*/

316

ResourceHandlerRegistration addResourceLocations(String... resourceLocations);

317

318

/**

319

* Set the cache control configuration for served resources.

320

* @param cacheControl the cache control configuration

321

* @return this registration for method chaining

322

*/

323

ResourceHandlerRegistration setCacheControl(CacheControl cacheControl);

324

325

/**

326

* Configure a resource chain for additional processing.

327

* @param cacheResources whether to cache resources

328

* @return the resource chain registration

329

*/

330

ResourceChainRegistration resourceChain(boolean cacheResources);

331

}

332

```

333

334

**Usage Examples:**

335

336

```java

337

@Override

338

public void addResourceHandlers(ResourceHandlerRegistry registry) {

339

// Serve static web assets

340

registry.addResourceHandler("/static/**")

341

.addResourceLocations("classpath:/static/", "file:/var/www/static/")

342

.setCacheControl(CacheControl.maxAge(Duration.ofDays(365))

343

.cachePublic()

344

.immutable());

345

346

// Serve uploads with shorter cache

347

registry.addResourceHandler("/uploads/**")

348

.addResourceLocations("file:/var/uploads/")

349

.setCacheControl(CacheControl.maxAge(Duration.ofHours(1)));

350

351

// Resource chain with versioning

352

registry.addResourceHandler("/assets/**")

353

.addResourceLocations("classpath:/assets/")

354

.resourceChain(true)

355

.addResolver(new VersionResourceResolver()

356

.addContentVersionStrategy("/**"));

357

}

358

```

359

360

### View Resolver Configuration

361

362

Registry for configuring view resolvers and rendering engines.

363

364

```java { .api }

365

class ViewResolverRegistry {

366

/**

367

* Register a FreeMarker view resolver.

368

* @return the view resolver registration

369

*/

370

UrlBasedViewResolverRegistration freeMarker();

371

372

/**

373

* Register a script template view resolver.

374

*/

375

void scriptTemplate();

376

377

/**

378

* Set default views to be added to every model.

379

* @param defaultViews the default views

380

*/

381

void defaultViews(View... defaultViews);

382

383

/**

384

* Set the order for view resolvers.

385

* @param order the order value

386

*/

387

void order(int order);

388

}

389

390

class UrlBasedViewResolverRegistration {

391

/**

392

* Set the prefix for view names.

393

* @param prefix the view name prefix

394

* @return this registration for method chaining

395

*/

396

UrlBasedViewResolverRegistration prefix(String prefix);

397

398

/**

399

* Set the suffix for view names.

400

* @param suffix the view name suffix

401

* @return this registration for method chaining

402

*/

403

UrlBasedViewResolverRegistration suffix(String suffix);

404

405

/**

406

* Set the view class to use.

407

* @param viewClass the view class

408

* @return this registration for method chaining

409

*/

410

UrlBasedViewResolverRegistration viewClass(Class<?> viewClass);

411

}

412

```

413

414

**Usage Examples:**

415

416

```java

417

@Override

418

public void configureViewResolvers(ViewResolverRegistry registry) {

419

// FreeMarker templates

420

registry.freeMarker()

421

.prefix("/templates/")

422

.suffix(".ftl");

423

424

// Script templates (e.g., Mustache, Handlebars)

425

registry.scriptTemplate();

426

427

// Default JSON view for API responses

428

registry.defaultViews(new MappingJackson2JsonView());

429

430

// Set resolver order

431

registry.order(1);

432

}

433

434

// FreeMarker configuration

435

@Bean

436

public FreeMarkerConfigurer freeMarkerConfigurer() {

437

FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();

438

configurer.setTemplateLoaderPath("classpath:/templates/");

439

configurer.setDefaultEncoding("UTF-8");

440

return configurer;

441

}

442

```

443

444

### Path Matching Configuration

445

446

Configuration for customizing path matching behavior.

447

448

```java { .api }

449

class PathMatchConfigurer {

450

/**

451

* Set whether to use case-sensitive path matching.

452

* @param caseSensitiveMatch true for case-sensitive matching

453

* @return this configurer for method chaining

454

*/

455

PathMatchConfigurer setUseCaseSensitiveMatch(Boolean caseSensitiveMatch);

456

457

/**

458

* Set whether to use trailing slash matching.

459

* @param trailingSlashMatch true to match trailing slashes

460

* @return this configurer for method chaining

461

*/

462

PathMatchConfigurer setUseTrailingSlashMatch(Boolean trailingSlashMatch);

463

464

/**

465

* Set a custom path matcher implementation.

466

* @param pathMatcher the path matcher to use

467

* @return this configurer for method chaining

468

*/

469

PathMatchConfigurer setPathMatcher(PathMatcher pathMatcher);

470

}

471

```

472

473

**Usage Examples:**

474

475

```java

476

@Override

477

public void configurePathMatching(PathMatchConfigurer configurer) {

478

configurer

479

.setUseCaseSensitiveMatch(false)

480

.setUseTrailingSlashMatch(true)

481

.setPathMatcher(new AntPathMatcher());

482

}

483

```

484

485

### Content Type Resolution Configuration

486

487

Builder for configuring how content types are resolved from requests.

488

489

```java { .api }

490

class RequestedContentTypeResolverBuilder {

491

/**

492

* Configure resolution via the "Accept" header.

493

* @return this builder for method chaining

494

*/

495

RequestedContentTypeResolverBuilder headerResolver();

496

497

/**

498

* Configure resolution via request parameter.

499

* @param parameterName the parameter name to check

500

* @return this builder for method chaining

501

*/

502

RequestedContentTypeResolverBuilder parameterResolver(String parameterName);

503

504

/**

505

* Configure resolution via path extension.

506

* @return this builder for method chaining

507

*/

508

RequestedContentTypeResolverBuilder pathExtensionResolver();

509

510

/**

511

* Set fixed content type resolver.

512

* @param mediaType the fixed media type

513

* @return this builder for method chaining

514

*/

515

RequestedContentTypeResolverBuilder fixedResolver(MediaType mediaType);

516

}

517

```

518

519

**Usage Examples:**

520

521

```java

522

@Override

523

public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) {

524

builder

525

.headerResolver() // Use Accept header

526

.parameterResolver("format") // Use ?format=json parameter

527

.pathExtensionResolver() // Use .json extension

528

.fixedResolver(MediaType.APPLICATION_JSON); // Fallback to JSON

529

}

530

```

531

532

### Argument Resolver Configuration

533

534

Configuration for custom argument resolvers in handler methods.

535

536

```java { .api }

537

class ArgumentResolverConfigurer {

538

/**

539

* Add a custom argument resolver.

540

* @param resolver the argument resolver to add

541

* @return this configurer for method chaining

542

*/

543

ArgumentResolverConfigurer addCustomResolver(HandlerMethodArgumentResolver resolver);

544

}

545

```

546

547

**Usage Examples:**

548

549

```java

550

@Override

551

public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {

552

configurer.addCustomResolver(new CustomUserArgumentResolver());

553

configurer.addCustomResolver(new TenantArgumentResolver());

554

}

555

556

// Custom argument resolver example

557

@Component

558

public class CustomUserArgumentResolver implements HandlerMethodArgumentResolver {

559

560

@Override

561

public boolean supportsParameter(MethodParameter parameter) {

562

return parameter.hasParameterAnnotation(CurrentUser.class) &&

563

User.class.isAssignableFrom(parameter.getParameterType());

564

}

565

566

@Override

567

public Mono<Object> resolveArgument(MethodParameter parameter,

568

BindingContext bindingContext,

569

ServerWebExchange exchange) {

570

return exchange.getPrincipal()

571

.cast(JwtAuthenticationToken.class)

572

.map(token -> extractUserFromToken(token));

573

}

574

}

575

```

576

577

### Blocking Execution Configuration

578

579

Configuration for handling blocking operations in reactive handlers.

580

581

```java { .api }

582

class BlockingExecutionConfigurer {

583

/**

584

* Configure the scheduler for blocking operations.

585

* @param scheduler the scheduler to use

586

* @return this configurer for method chaining

587

*/

588

BlockingExecutionConfigurer scheduler(Scheduler scheduler);

589

}

590

```

591

592

**Usage Examples:**

593

594

```java

595

@Override

596

public void configureBlockingExecution(BlockingExecutionConfigurer configurer) {

597

// Use custom scheduler for blocking operations

598

Scheduler blockingScheduler = Schedulers.newBoundedElastic(

599

10, // Thread cap

600

100000, // Queue size

601

"blocking-thread"

602

);

603

604

configurer.scheduler(blockingScheduler);

605

}

606

```