How to Quickly Integrate SpringDoc for OpenAPI Docs in Spring Boot
This article walks through why SpringDoc replaces SpringFox, shows step‑by‑step minimal configuration, dependency setup, controller annotations, API grouping (both programmatic and declarative), and necessary adjustments for WebMvcConfigurer and Spring Security to generate OpenAPI 3 documentation in a Spring Boot project.
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 configuration at runtime, producing JSON/YAML/HTML documentation and embedding an interactive Swagger UI for developers to view and test APIs.
Relationship with Swagger
Swagger introduced the original OpenAPI design ideas and provides the Swagger UI for interactive documentation. SpringDoc is not a replacement for Swagger; rather, it implements the OpenAPI 3 standard and integrates Swagger UI natively as the documentation front‑end.
Why Choose SpringDoc?
Before SpringDoc, the Spring ecosystem used SpringFox to integrate Swagger. SpringFox stopped receiving updates around 2020 and cannot adapt to Spring Boot 2.6+ or 3.x, leading to path‑matching failures and annotation incompatibilities. SpringDoc supports Spring Boot 2.6+, 3.x (including JDK 17+), and OpenAPI 3 out of the box. It also uses standard JSR‑303 annotations such as @Schema and @Parameter, reducing the learning curve compared with SpringFox’s proprietary annotations like @ApiModel.
Minimal Configuration – Getting Started
Minimal configuration usage
Below is the simplest way to add SpringDoc to a project.
Step 1: Add the Maven/Gradle dependency
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- recommended to use the latest version -->
</dependency>Step 2: (Optional) Minimal application.yml
# application.yml
springdoc:
packages-to-scan: com.example.controller # defaults to scanning the whole classpath
swagger-ui:
enabled: true
path: /swagger-ui/index.html
api-docs:
enabled: true
path: /api-docsWith only this dependency and optional YAML, the Swagger UI is reachable at http://localhost:8080/swagger-ui/index.html. If the project has no controllers, the UI will show an empty page.
Step 3: Add annotations to a controller
Without annotations:
@RestController
@RequestMapping("/main")
public class MainController {
@GetMapping("/index")
public String index(String str1) {
return "请求成功";
}
}With SpringDoc annotations:
@RestController
@RequestMapping("/main")
@Tag(name = "演示controller", description = "演示controller")
public class MainController {
@GetMapping("/index")
@Operation(summary = "演示方法", description = "演示方法的注释")
public String index(@Parameter(description = "参数1", required = true) String str1) {
return "请求成功";
}
}After adding the annotations, the method details appear in the generated UI.
Advanced Feature – API Grouping
SpringDoc supports grouping APIs so that different modules appear under separate tabs.
Programmatic Grouping (Bean configuration)
@Configuration
@OpenAPIDefinition(info = @Info(
title = "项目API文档",
version = "1.0",
description = "SpringBoot项目接口文档"))
public class SpringDocConfig {
/**
* 商品分组 – path‑based scanning
*/
@Bean
public GroupedOpenApi userGroup() {
// Only include /api/product/** endpoints
return GroupedOpenApi.builder()
.group("商品模块")
.pathsToMatch("/api/product/**")
.build();
}
/**
* 会员分组 – package‑based scanning
*/
@Bean
public GroupedOpenApi productGroup() {
// Scan the package com.ren.main.controller.member
return GroupedOpenApi.builder()
.group("用户模块")
.packagesToScan("com.ren.main.controller.member")
.build();
}
}SpringDoc discovers GroupedOpenApi beans at startup and creates the corresponding groups. If multiple groups match the same endpoint, the endpoint appears in each group.
Declarative Grouping (application.yml)
springdoc:
group-configs:
- group: '默认分组'
paths-to-match: '/**'
- group: '商品模块'
paths-to-match: '/api/product/**'
- group: '用户模块'
packages-to-scan: 'com.ren.main.controller.member'This YAML produces the same UI layout as the programmatic approach, but keeps configuration centralized and can be split across environments.
Handling WebMvcConfigurer Customizations
If a project overrides WebMvcConfigurer.addResourceHandlers, Spring’s default static‑resource mappings (including those required by Swagger UI) are lost. The following configuration restores the Swagger UI resources:
@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());
}
}Integrating with Spring Security
When Spring Security is present, unauthenticated requests cannot reach the documentation endpoints. The security filter chain must whitelist the static resources and the OpenAPI endpoints:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
// Allow OPTIONS for CORS pre‑flight
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// Allow static resources used by Swagger UI
.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 adding this configuration, the documentation UI is accessible without authentication.
Conclusion
The guide demonstrates the complete workflow for integrating SpringDoc into a Spring Boot project: from adding the starter dependency, configuring minimal YAML, annotating controllers, defining API groups (both programmatically and declaratively), to handling custom WebMvcConfigurer and Spring Security setups. This enables developers to generate clean OpenAPI 3 documentation with zero‑configuration defaults while retaining full control when needed.
Java Web Project
Focused on Java backend technologies, trending internet tech, and the latest industry developments. The platform serves over 200,000 Java developers, inviting you to learn and exchange ideas together. Check the menu for Java learning resources.
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.
