0
# Web MVC Configuration
1
2
Spring Web MVC configuration that sets up resource handlers, path mapping, and static asset serving for Swagger UI components. This configuration ensures that Swagger UI assets are properly served and accessible through the web application.
3
4
## Capabilities
5
6
### SwaggerWebMvcConfigurer
7
8
Web MVC configurer that handles resource serving and transformation for Swagger UI static assets.
9
10
```java { .api }
11
/**
12
* Spring Web MVC configurer for Swagger UI resource handling
13
* Configures resource handlers to serve Swagger UI static assets from web jars
14
*/
15
public class SwaggerWebMvcConfigurer implements WebMvcConfigurer {
16
17
/**
18
* Constructor for Web MVC configurer
19
* @param swaggerUiConfigProperties Swagger UI configuration properties
20
* @param swaggerIndexTransformer Transformer for dynamic content injection
21
* @param actuatorProvider Optional actuator provider for management port support
22
* @param swaggerResourceResolver Resource resolver for web jar assets
23
*/
24
public SwaggerWebMvcConfigurer(SwaggerUiConfigProperties swaggerUiConfigProperties,
25
SwaggerIndexTransformer swaggerIndexTransformer, Optional<ActuatorProvider> actuatorProvider,
26
SwaggerResourceResolver swaggerResourceResolver);
27
28
/**
29
* Configures resource handlers for Swagger UI static assets
30
* Sets up resource locations, caching, and transformation pipeline
31
* @param registry Spring resource handler registry
32
*/
33
@Override
34
public void addResourceHandlers(ResourceHandlerRegistry registry);
35
36
// Empty implementations for Spring 4 compatibility:
37
public void configurePathMatch(PathMatchConfigurer configurer);
38
public void configureContentNegotiation(ContentNegotiationConfigurer configurer);
39
public void configureAsyncSupport(AsyncSupportConfigurer configurer);
40
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
41
public void addFormatters(FormatterRegistry registry);
42
public void addInterceptors(InterceptorRegistry registry);
43
public void addCorsMappings(CorsRegistry registry);
44
public void addViewControllers(ViewControllerRegistry registry);
45
public void configureViewResolvers(ViewResolverRegistry registry);
46
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers);
47
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers);
48
public void configureMessageConverters(List<HttpMessageConverter<?>> converters);
49
public void extendMessageConverters(List<HttpMessageConverter<?>> converters);
50
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers);
51
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers);
52
@Nullable
53
public Validator getValidator();
54
@Nullable
55
public MessageCodesResolver getMessageCodesResolver();
56
}
57
```
58
59
## Resource Handler Configuration
60
61
The `addResourceHandlers` method configures two primary resource handlers for Swagger UI assets:
62
63
### Handler 1: Swagger Initializer JavaScript
64
65
Handles the main Swagger UI initializer JavaScript file with dynamic configuration injection:
66
67
```java
68
// Resource pattern: {uiRootPath}/swagger-ui/*/*/swagger-initializer.js
69
registry.addResourceHandler(uiRootPath + "/swagger-ui/*/*/swagger-initializer.js")
70
.addResourceLocations("classpath:/META-INF/resources/webjars/")
71
.setCachePeriod(0) // Disable caching for dynamic content
72
.resourceChain(false)
73
.addResolver(swaggerResourceResolver)
74
.addTransformer(swaggerIndexTransformer); // Injects runtime configuration
75
```
76
77
### Handler 2: General Swagger UI Assets
78
79
Handles all other Swagger UI static assets (CSS, JS, images, etc.):
80
81
```java
82
// Resource pattern: {uiRootPath}/swagger-ui/*/**
83
registry.addResourceHandler(uiRootPath + "/swagger-ui/*/**")
84
.addResourceLocations("classpath:/META-INF/resources/webjars/")
85
.resourceChain(false)
86
.addResolver(swaggerResourceResolver)
87
.addTransformer(swaggerIndexTransformer);
88
```
89
90
## Path Resolution Logic
91
92
The configurer dynamically calculates resource handler paths based on configuration and environment:
93
94
```java { .api }
95
/**
96
* Path calculation logic used in addResourceHandlers
97
*/
98
StringBuilder uiRootPath = new StringBuilder();
99
String swaggerPath = swaggerUiConfigProperties.getPath(); // e.g., "/swagger-ui.html"
100
101
// Extract root path from Swagger UI path
102
if (swaggerPath.contains("/")) {
103
uiRootPath.append(swaggerPath, 0, swaggerPath.lastIndexOf("/"));
104
}
105
106
// Add actuator base path if using management port
107
if (actuatorProvider.isPresent() && actuatorProvider.get().isUseManagementPort()) {
108
uiRootPath.append(actuatorProvider.get().getBasePath()); // e.g., "/actuator"
109
}
110
111
// Final patterns:
112
// Standard: "/swagger-ui/*/**"
113
// With actuator: "/actuator/swagger-ui/*/**"
114
// With custom path: "/custom/ui/*/**"
115
```
116
117
## Resource Chain Configuration
118
119
Each resource handler is configured with a specific resource chain:
120
121
```java { .api }
122
/**
123
* Resource chain configuration components
124
*/
125
interface ResourceChainConfig {
126
/**
127
* Resource locations where assets are stored
128
*/
129
String CLASSPATH_RESOURCE_LOCATION = "classpath:/META-INF/resources/webjars/";
130
131
/**
132
* Cache period for resources (0 = no cache for dynamic content)
133
*/
134
int CACHE_PERIOD = 0;
135
136
/**
137
* Resource chain disabled for direct resolution
138
*/
139
boolean RESOURCE_CHAIN_ENABLED = false;
140
}
141
```
142
143
### Resource Resolution Order
144
145
1. **SwaggerResourceResolver**: Resolves web jar paths and versions
146
2. **SwaggerIndexTransformer**: Transforms content for dynamic configuration
147
148
## Usage Examples
149
150
### Basic Resource Serving
151
152
The configuration automatically serves Swagger UI assets:
153
154
```java
155
// These URLs are automatically handled:
156
// /swagger-ui/swagger-ui-bundle.js
157
// /swagger-ui/swagger-ui-standalone-preset.js
158
// /swagger-ui/swagger-ui.css
159
// /swagger-ui/swagger-initializer.js (with dynamic config)
160
```
161
162
### Custom Path Configuration
163
164
Configure custom Swagger UI paths:
165
166
```yaml
167
springdoc:
168
swagger-ui:
169
path: /api-docs/ui.html
170
```
171
172
```java
173
// Resource handlers automatically adapt:
174
// /api-docs/swagger-ui/*/** → Swagger UI assets
175
// /api-docs/swagger-ui/*/*/swagger-initializer.js → Dynamic initializer
176
```
177
178
### Actuator Integration
179
180
When using management port, paths include actuator base path:
181
182
```yaml
183
management:
184
server:
185
port: 8081
186
endpoints:
187
web:
188
base-path: /mgmt
189
springdoc:
190
use-management-port: true
191
```
192
193
```java
194
// Resource handlers include actuator path:
195
// /mgmt/swagger-ui/*/** → Swagger UI assets on management port
196
```
197
198
### Custom Resource Handling
199
200
Override resource configuration for specific requirements:
201
202
```java
203
@Configuration
204
public class CustomSwaggerResourceConfig {
205
206
@Bean
207
public WebMvcConfigurer customSwaggerResourceConfigurer() {
208
return new WebMvcConfigurer() {
209
@Override
210
public void addResourceHandlers(ResourceHandlerRegistry registry) {
211
registry.addResourceHandler("/custom-swagger/**")
212
.addResourceLocations("classpath:/custom-swagger-ui/")
213
.setCachePeriod(3600); // 1 hour cache
214
}
215
};
216
}
217
}
218
```
219
220
### Resource Caching Configuration
221
222
Control caching behavior for different environments:
223
224
```java
225
@Configuration
226
@Profile("production")
227
public class ProductionSwaggerConfig {
228
229
@Bean
230
@Primary
231
public SwaggerWebMvcConfigurer productionSwaggerConfigurer(
232
SwaggerUiConfigProperties properties,
233
SwaggerIndexTransformer transformer,
234
Optional<ActuatorProvider> actuatorProvider,
235
SwaggerResourceResolver resolver) {
236
237
return new SwaggerWebMvcConfigurer(properties, transformer, actuatorProvider, resolver) {
238
@Override
239
public void addResourceHandlers(ResourceHandlerRegistry registry) {
240
// Configure with longer cache periods for production
241
super.addResourceHandlers(registry);
242
243
// Additional production-specific resource handling
244
registry.addResourceHandler("/swagger-ui/static/**")
245
.addResourceLocations("classpath:/static/swagger/")
246
.setCachePeriod(86400); // 24 hour cache
247
}
248
};
249
}
250
}
251
```
252
253
## Integration with Spring Boot
254
255
The Web MVC configuration integrates seamlessly with Spring Boot's auto-configuration:
256
257
```java { .api }
258
/**
259
* Integration points with Spring Boot
260
*/
261
interface SpringBootIntegration {
262
/**
263
* Automatically registered through SwaggerConfig auto-configuration
264
*/
265
void autoRegistration();
266
267
/**
268
* Respects Spring Boot's resource handling configuration
269
*/
270
void springBootResourceConfig();
271
272
/**
273
* Works with Spring Boot's caching and compression settings
274
*/
275
void springBootOptimizations();
276
277
/**
278
* Compatible with Spring Boot DevTools for development
279
*/
280
void devToolsSupport();
281
}
282
```
283
284
## Performance Considerations
285
286
### Resource Caching
287
288
- **Development**: Cache period set to 0 for immediate updates
289
- **Production**: Consider longer cache periods for static assets
290
- **Dynamic Content**: Initializer JavaScript always has cache disabled
291
292
### Resource Chain Optimization
293
294
- **Resource Chain Disabled**: Direct resolution for better performance
295
- **Resolver Order**: Custom resolver first, then fallback to default
296
- **Transformer Pipeline**: Minimal transformation overhead
297
298
### Asset Optimization
299
300
```java
301
// Consider enabling Spring Boot's resource optimization in production:
302
spring:
303
resources:
304
chain:
305
strategy:
306
content:
307
enabled: true # Content-based versioning
308
compressed: true # Serve pre-compressed assets
309
cache:
310
cachecontrol:
311
max-age: 86400 # 24 hour cache for static assets
312
```