CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springdoc--springdoc-openapi

Java library that automates OpenAPI 3 documentation generation for Spring Boot applications with seamless Swagger UI integration

Pending
Overview
Eval results
Files

web-configuration.mddocs/

Web MVC Configuration

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.

Capabilities

SwaggerWebMvcConfigurer

Web MVC configurer that handles resource serving and transformation for Swagger UI static assets.

/**
 * Spring Web MVC configurer for Swagger UI resource handling
 * Configures resource handlers to serve Swagger UI static assets from web jars
 */
public class SwaggerWebMvcConfigurer implements WebMvcConfigurer {
    
    /**
     * Constructor for Web MVC configurer
     * @param swaggerUiConfigProperties Swagger UI configuration properties
     * @param swaggerIndexTransformer Transformer for dynamic content injection
     * @param actuatorProvider Optional actuator provider for management port support
     * @param swaggerResourceResolver Resource resolver for web jar assets
     */
    public SwaggerWebMvcConfigurer(SwaggerUiConfigProperties swaggerUiConfigProperties,
        SwaggerIndexTransformer swaggerIndexTransformer, Optional<ActuatorProvider> actuatorProvider, 
        SwaggerResourceResolver swaggerResourceResolver);

    /**
     * Configures resource handlers for Swagger UI static assets
     * Sets up resource locations, caching, and transformation pipeline
     * @param registry Spring resource handler registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry);

    // Empty implementations for Spring 4 compatibility:
    public void configurePathMatch(PathMatchConfigurer configurer);
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer);
    public void configureAsyncSupport(AsyncSupportConfigurer configurer);
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
    public void addFormatters(FormatterRegistry registry);
    public void addInterceptors(InterceptorRegistry registry);
    public void addCorsMappings(CorsRegistry registry);
    public void addViewControllers(ViewControllerRegistry registry);
    public void configureViewResolvers(ViewResolverRegistry registry);
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers);
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers);
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters);
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters);
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers);
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers);
    @Nullable
    public Validator getValidator();
    @Nullable
    public MessageCodesResolver getMessageCodesResolver();
}

Resource Handler Configuration

The addResourceHandlers method configures two primary resource handlers for Swagger UI assets:

Handler 1: Swagger Initializer JavaScript

Handles the main Swagger UI initializer JavaScript file with dynamic configuration injection:

// Resource pattern: {uiRootPath}/swagger-ui/*/*/swagger-initializer.js
registry.addResourceHandler(uiRootPath + "/swagger-ui/*/*/swagger-initializer.js")
    .addResourceLocations("classpath:/META-INF/resources/webjars/")
    .setCachePeriod(0)  // Disable caching for dynamic content
    .resourceChain(false)
    .addResolver(swaggerResourceResolver)
    .addTransformer(swaggerIndexTransformer);  // Injects runtime configuration

Handler 2: General Swagger UI Assets

Handles all other Swagger UI static assets (CSS, JS, images, etc.):

// Resource pattern: {uiRootPath}/swagger-ui/*/**
registry.addResourceHandler(uiRootPath + "/swagger-ui/*/**")
    .addResourceLocations("classpath:/META-INF/resources/webjars/")
    .resourceChain(false)
    .addResolver(swaggerResourceResolver)
    .addTransformer(swaggerIndexTransformer);

Path Resolution Logic

The configurer dynamically calculates resource handler paths based on configuration and environment:

/**
 * Path calculation logic used in addResourceHandlers
 */
StringBuilder uiRootPath = new StringBuilder();
String swaggerPath = swaggerUiConfigProperties.getPath();  // e.g., "/swagger-ui.html"

// Extract root path from Swagger UI path
if (swaggerPath.contains("/")) {
    uiRootPath.append(swaggerPath, 0, swaggerPath.lastIndexOf("/"));
}

// Add actuator base path if using management port
if (actuatorProvider.isPresent() && actuatorProvider.get().isUseManagementPort()) {
    uiRootPath.append(actuatorProvider.get().getBasePath());  // e.g., "/actuator"
}

// Final patterns:
// Standard: "/swagger-ui/*/**"
// With actuator: "/actuator/swagger-ui/*/**"
// With custom path: "/custom/ui/*/**"

Resource Chain Configuration

Each resource handler is configured with a specific resource chain:

/**
 * Resource chain configuration components
 */
interface ResourceChainConfig {
    /**
     * Resource locations where assets are stored
     */
    String CLASSPATH_RESOURCE_LOCATION = "classpath:/META-INF/resources/webjars/";
    
    /**
     * Cache period for resources (0 = no cache for dynamic content)
     */
    int CACHE_PERIOD = 0;
    
    /**
     * Resource chain disabled for direct resolution
     */
    boolean RESOURCE_CHAIN_ENABLED = false;
}

Resource Resolution Order

  1. SwaggerResourceResolver: Resolves web jar paths and versions
  2. SwaggerIndexTransformer: Transforms content for dynamic configuration

Usage Examples

Basic Resource Serving

The configuration automatically serves Swagger UI assets:

// These URLs are automatically handled:
// /swagger-ui/swagger-ui-bundle.js
// /swagger-ui/swagger-ui-standalone-preset.js  
// /swagger-ui/swagger-ui.css
// /swagger-ui/swagger-initializer.js (with dynamic config)

Custom Path Configuration

Configure custom Swagger UI paths:

springdoc:
  swagger-ui:
    path: /api-docs/ui.html
// Resource handlers automatically adapt:
// /api-docs/swagger-ui/*/** → Swagger UI assets
// /api-docs/swagger-ui/*/*/swagger-initializer.js → Dynamic initializer

Actuator Integration

When using management port, paths include actuator base path:

management:
  server:
    port: 8081
  endpoints:
    web:
      base-path: /mgmt
springdoc:
  use-management-port: true
// Resource handlers include actuator path:
// /mgmt/swagger-ui/*/** → Swagger UI assets on management port

Custom Resource Handling

Override resource configuration for specific requirements:

@Configuration
public class CustomSwaggerResourceConfig {
    
    @Bean
    public WebMvcConfigurer customSwaggerResourceConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/custom-swagger/**")
                    .addResourceLocations("classpath:/custom-swagger-ui/")
                    .setCachePeriod(3600);  // 1 hour cache
            }
        };
    }
}

Resource Caching Configuration

Control caching behavior for different environments:

@Configuration
@Profile("production")
public class ProductionSwaggerConfig {
    
    @Bean
    @Primary
    public SwaggerWebMvcConfigurer productionSwaggerConfigurer(
        SwaggerUiConfigProperties properties,
        SwaggerIndexTransformer transformer,
        Optional<ActuatorProvider> actuatorProvider,
        SwaggerResourceResolver resolver) {
        
        return new SwaggerWebMvcConfigurer(properties, transformer, actuatorProvider, resolver) {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                // Configure with longer cache periods for production
                super.addResourceHandlers(registry);
                
                // Additional production-specific resource handling
                registry.addResourceHandler("/swagger-ui/static/**")
                    .addResourceLocations("classpath:/static/swagger/")
                    .setCachePeriod(86400);  // 24 hour cache
            }
        };
    }
}

Integration with Spring Boot

The Web MVC configuration integrates seamlessly with Spring Boot's auto-configuration:

/**
 * Integration points with Spring Boot
 */
interface SpringBootIntegration {
    /**
     * Automatically registered through SwaggerConfig auto-configuration
     */
    void autoRegistration();
    
    /**
     * Respects Spring Boot's resource handling configuration
     */
    void springBootResourceConfig();
    
    /**
     * Works with Spring Boot's caching and compression settings
     */
    void springBootOptimizations();
    
    /**
     * Compatible with Spring Boot DevTools for development
     */
    void devToolsSupport();
}

Performance Considerations

Resource Caching

  • Development: Cache period set to 0 for immediate updates
  • Production: Consider longer cache periods for static assets
  • Dynamic Content: Initializer JavaScript always has cache disabled

Resource Chain Optimization

  • Resource Chain Disabled: Direct resolution for better performance
  • Resolver Order: Custom resolver first, then fallback to default
  • Transformer Pipeline: Minimal transformation overhead

Asset Optimization

// Consider enabling Spring Boot's resource optimization in production:
spring:
  resources:
    chain:
      strategy:
        content:
          enabled: true  # Content-based versioning
      compressed: true   # Serve pre-compressed assets
    cache:
      cachecontrol:
        max-age: 86400   # 24 hour cache for static assets

Install with Tessl CLI

npx tessl i tessl/maven-org-springdoc--springdoc-openapi

docs

auto-configuration.md

controllers.md

core-api-generation.md

index.md

resource-processing.md

web-configuration.md

tile.json