Spring Boot 3.2.5集成SpringDoc时Swagger UI提示无API定义的解决方法
问题:Swagger UI显示“未提供API定义”
错误提示
未提供API定义。
问题描述
我有一个Spring Boot 3.2.5版本的应用,添加了以下Swagger依赖:
<!-- SWAGGER --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.5.0</version> </dependency>
之后在application.properties中添加了以下配置:
# Spring Docs API路径 springdoc.api-docs.path=/swagger/api-docs # Spring Docs Swagger UI路径 springdoc.swagger-ui.path=/swagger-ui.html # Spring Docs排序规则 springdoc.swagger-ui.operationsSorter=method # 设置UI获取配置的URL springdoc.swagger-ui.configUrl=/swagger/api-docs
启动应用后,访问http://localhost:10110/swagger-ui/index.html时,页面显示:
No API definition provided.
但访问http://localhost:10110/时,可以看到所有接口的JSON数据。
如何解决这个问题?
解决方案
1. 修正Swagger UI配置错误
你当前错误地使用了springdoc.swagger-ui.configUrl,这个参数是用来指定Swagger UI自身配置文件的路径,而非API文档的地址。正确应该用springdoc.swagger-ui.url来关联你的API文档路径:
修改application.properties:
# 移除错误的configUrl配置 # springdoc.swagger-ui.configUrl=/swagger/api-docs # 添加正确的url配置,指向API文档路径 springdoc.swagger-ui.url=/swagger/api-docs
2. 放开Spring Security对Swagger路径的拦截
你的项目引入了Spring Security,必须确保Swagger相关路径允许匿名访问,否则UI无法获取API文档。添加以下配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth // 允许Swagger相关路径匿名访问 .requestMatchers("/swagger/**", "/swagger-ui/**", "/v3/api-docs/**") .permitAll() // 其他路径保持原有认证规则 .anyRequest().authenticated() ); // 测试环境可禁用CSRF以避免Swagger请求被拦截 http.csrf(csrf -> csrf.disable()); return http.build(); } }
3. 验证API文档路径正确性
确保http://localhost:10110/swagger/api-docs能正常返回OpenAPI格式的JSON数据。如果根路径/返回的是Spring Data REST的默认文档,说明需要明确指定SpringDoc的扫描范围:
import org.springframework.context.annotation.Configuration; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.info.Info; @Configuration @OpenAPIDefinition(info = @Info(title = "Acme API", version = "1.0")) public class OpenApiConfig { // 如需指定扫描的控制器包,可添加以下Bean /* @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info().title("Acme API").version("1.0")); } */ }
4. 访问正确的Swagger UI路径
修改配置后重启应用,访问你配置的UI路径http://localhost:10110/swagger-ui.html,而非/swagger-ui/index.html。
内容的提问来源于stack exchange,提问作者KenobiBastila
相关产品推荐
相关产品推荐

