SpringDoc Tutorial: Modern OpenAPI 3 Documentation for Spring Boot
This tutorial introduces SpringDoc as a modern replacement for SpringFox/Swagger UI in Spring Boot projects, covering zero-config setup, programmatic and declarative API grouping, handling WebMvcConfigurer and Spring Security conflicts, with code examples for OpenAPI 3 compliance.
What is SpringDoc
SpringDoc is a library designed for Spring Boot applications that automatically generates API documentation compliant with the OpenAPI 3 specification. It scans controllers, method annotations, and configurations to produce JSON, YAML, or HTML documentation and provides an interactive interface (Swagger UI) for viewing and testing APIs.
Relationship with Swagger
Swagger, the predecessor to the OpenAPI specification, contributed the design philosophy and drove standardization. Its core tool, Swagger UI, renders interactive documentation. SpringDoc is not a replacement for Swagger but an implementation tool based on OpenAPI 3 that natively integrates Swagger UI as the documentation frontend.
Why Choose SpringDoc Over SpringFox
Before SpringDoc, SpringFox was the standard integration for Swagger in the Spring ecosystem. SpringFox performed runtime scanning of Spring MVC controllers (e.g., @RestController, @RequestMapping) and Swagger-specific annotations (e.g., @ApiOperation), converted results to Swagger 2.0 or OpenAPI 3.0 JSON, and offered a Docket configuration class for customizing scan paths and document metadata. Swagger UI then rendered that JSON at http://localhost:8080/swagger-ui.html with interactive testing.
However, around 2020 SpringFox maintenance effectively stopped: no new releases, no fixes, and incompatibility with Spring Boot 2.6+ and 3.x (path matching failures, annotation conflicts). Its complex configuration also drove adoption away. SpringDoc takes over with full support for Spring Boot 2.6+ and 3.x (including JDK 17+), native OpenAPI 3 support, zero-config startup (just add one dependency), and uses standard JSR-303 annotations ( @Schema, @Parameter) instead of SpringFox-proprietary ones ( @ApiModel), reducing learning overhead.
Minimal Configuration (Four Steps)
Step 1: Add Dependency
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- use latest version -->
</dependency>Step 2: Configuration File (Optional Defaults)
The following application.yml shows key defaults; minimal setup requires no configuration at all.
springdoc:
packages-to-scan: com.example.controller # default: scan entire classpath
swagger-ui:
enabled: true
path: /swagger-ui/index.html
url: /v3/api-docs
disable-swagger-default-url: false
api-docs:
enabled: true
path: /api-docsStep 3: Basic Info Configuration Class
@Configuration
@OpenAPIDefinition(info = @Info(
title = "Project API Documentation",
version = "1.0",
description = "Spring Boot Project API Documentation"
))
public class SpringDocConfig {
// no extra config needed
}Step 4: Annotate Controller Methods
Without annotations the UI shows only raw paths. Adding @Tag, @Operation, and @Parameter enriches the display.
@RestController
@RequestMapping("/main")
@Tag(name = "Demo Controller", description = "Demo controller")
public class MainController {
@GetMapping("/index")
@Operation(summary = "Demo Method", description = "Demo method description")
public String index(
@Parameter(description = "Parameter 1", required = true) String str1) {
return "Success";
}
}Access the UI at http://localhost:8080/swagger-ui/index.html (adjust if defaults changed). Note: this minimal setup assumes no filters, interceptors, or Spring Security; otherwise additional configuration is required.
API Grouping Configuration
Grouping organizes endpoints into logical modules (e.g., Product, User). Two approaches are provided.
Approach 1: Programmatic Configuration (Flexible, Extensible, Debug-Friendly)
Define GroupedOpenApi beans. SpringDoc detects these beans at startup and creates groups.
@Configuration
@OpenAPIDefinition(info = @Info(...))
public class SpringDocConfig {
@Bean
public GroupedOpenApi productGroup() {
return GroupedOpenApi.builder()
.group("Product Module")
.pathsToMatch("/api/product/**")
.build();
}
@Bean
public GroupedOpenApi userGroup() {
return GroupedOpenApi.builder()
.group("User Module")
.packagesToScan("com.ren.main.controller.member")
.build();
}
}Important behaviors:
Once any GroupedOpenApi bean exists, springdoc.packages-to-scan in YAML is ignored (group scan priority > config file).
Two scan modes: path matching ( pathsToMatch) and package scanning ( packagesToScan).
If an endpoint matches multiple groups, it appears in each.
In the example, a MainController outside grouped paths disappeared. Adding a default group with pathsToMatch("/**") restores it, and overlapping endpoints appear in multiple groups.
Approach 2: Declarative Configuration (Centralized, Multi-Profile Friendly)
springdoc:
group-configs:
- group: 'Default Group'
paths-to-match: '/**'
- group: 'Product Module'
paths-to-match: '/api/product/**'
- group: 'User Module'
packages-to-scan: 'com.ren.main.controller.member'Produces identical UI grouping.
Handling Custom WebMvcConfigurer
If the project overrides addResourceHandlers, Spring's default static resource mappings are lost, breaking Swagger UI. Restore SpringDoc's resources by adding:
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springdoc-openapi-ui/")
.setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic());
}
}Note: SpringDoc's resource path differs from the older SpringFox.
Handling Spring Security
Spring Security blocks unauthenticated access to all endpoints, including Swagger UI and OpenAPI docs. Permit the required paths in the security filter chain:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers(request -> {
String path = request.getServletPath();
return request.getMethod().equals("GET") && (
"/".equals(path) || path.endsWith(".html") ||
path.endsWith(".css") || path.endsWith(".js"));
}).permitAll()
.requestMatchers(
"/swagger-ui/**",
"/*/api-docs/**",
"/swagger-resources/**",
"/webjars/**",
"/druid/**"
).permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}After this, Swagger UI and API docs are accessible without authentication.
Summary
This article walked through integrating SpringDoc into a Spring Boot project: why it replaces the unmaintained SpringFox, minimal four-step setup, two grouping strategies with their precedence rules, and solutions for common conflicts with WebMvcConfigurer and Spring Security. All configurations use OpenAPI 3 standard annotations and work with Spring Boot 3.x and JDK 17+.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
