Spring Boot3升级后springdoc-openapi仅加载示例数据,@Tag注解失效
解决Spring Boot 3升级后SpringDoc无法识别@Tag注解的问题
以下是针对你遇到问题的具体排查和解决步骤:
1. 确认@Tag注解的包路径
Spring Boot 3对应的OpenAPI 3规范中,正确的@Tag注解包为io.swagger.v3.oas.annotations.tags.Tag,请检查你的控制器类是否误用了旧版Swagger 2的io.swagger.annotations.Tag(该注解在OpenAPI 3环境下不会被识别)。
2. 配置SpringDoc的API扫描范围
在app.yml中明确指定需要扫描的控制器包路径或API路径前缀,确保SpringDoc能找到你的REST控制器:
springdoc: swagger-ui: enabled: true config-url: /api-app/v3/api-docs/swagger-config disable-swagger-default-url: true # 指定控制器所在的包路径,替换为你的实际包名 packages-to-scan: com.yourcompany.yourapp.controller # 匹配你的API路径前缀,确保覆盖所有接口 paths-to-match: /api-app/**
3. 检查Spring Security拦截规则
如果你的应用使用Spring Security,需要允许Swagger相关路径的匿名访问,否则SpringDoc无法生成API文档:
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth // 允许访问Swagger相关路径 .requestMatchers("/api-app/v3/api-docs/**", "/api-app/swagger-ui/**") .permitAll() // 其他接口按原有规则配置 .anyRequest().authenticated() ); return http.build(); }
4. 验证API文档接口的可访问性
直接访问www.example.com/api-app/v3/api-docs,检查返回的JSON数据中是否包含tags字段以及你的控制器对应的标签信息:
- 如果返回的JSON中没有
tags,说明SpringDoc未扫描到控制器,需检查packages-to-scan或paths-to-match配置是否正确 - 如果JSON中有
tags但Swagger UI不显示,需确认config-url配置的路径是否能正常返回Swagger配置JSON
5. 清理依赖冲突
确保你的Gradle依赖中只有新版SpringDoc依赖,排除旧版的冲突依赖:
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' // 排除可能存在的旧版SpringDoc依赖 configurations.all { exclude group: 'org.springdoc', module: 'springdoc-openapi-ui' }
6. 添加OpenAPI配置类(可选)
手动创建OpenAPI配置类,显式定义API文档的基础信息,同时确保SpringDoc能识别全局配置:
import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.info.Info; import org.springframework.context.annotation.Configuration; @Configuration @OpenAPIDefinition( info = @Info( title = "你的应用API文档", version = "v1", description = "应用API功能描述" ) ) public class OpenApiConfig { }
内容的提问来源于stack exchange,提问作者Ryan Dollar
相关产品推荐
相关产品推荐

