Spring Boot集成OpenAPI 3.0 swagger-ui遇无法推断base URL问题求解决
问题场景
已添加Maven依赖:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.7.0</version> </dependency>
访问/swagger-ui.html时弹出提示:
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
当前OpenAPI配置类:
@Configuration public class OpenApiConfiguration { @Bean public OpenAPI customOpenAPI() { return new OpenAPI().info(apiInfo()); } private Info apiInfo() { return new Info() .title(API_INFO_TITLE) .description(API_INFO_DESC) .version(API_INFO_VER) .license(apiLicence()); } }
可行解决办法
1. 配置应用上下文路径与Swagger对应参数
如果应用设置了server.servlet.context-path(比如/api),需在配置文件中指定Swagger的路径匹配规则:application.properties配置:
springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.base-url=/api
或application.yml配置:
springdoc: api-docs: path: /v3/api-docs swagger-ui: base-url: /api
2. 放行Spring Security中的Swagger资源
若项目集成Spring Security,需在配置类中允许访问Swagger相关路径:
Spring Security 5.7以下版本:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**") .permitAll() .anyRequest() .authenticated(); } }
Spring Security 5.7+版本(使用SecurityFilterChain):
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**") .permitAll() .anyRequest() .authenticated()); return http.build(); } }
3. 显式指定Swagger UI的API文档路径
在OpenAPI配置类中添加SwaggerUiConfigParameters Bean,明确API文档地址:
@Configuration public class OpenApiConfiguration { @Bean public OpenAPI customOpenAPI() { return new OpenAPI().info(apiInfo()); } private Info apiInfo() { return new Info() .title(API_INFO_TITLE) .description(API_INFO_DESC) .version(API_INFO_VER) .license(apiLicence()); } @Bean public SwaggerUiConfigParameters swaggerUiConfigParameters() { SwaggerUiConfigParameters params = new SwaggerUiConfigParameters(); params.setUrl("/v3/api-docs"); // 若有上下文路径则写全,比如/api/v3/api-docs return params; } }
4. 升级springdoc-openapi-ui版本
1.7.0版本存在已知兼容性问题,建议升级到与Spring Boot版本匹配的稳定版:
- Spring Boot 2.x对应springdoc 1.x系列(如1.6.14)
- Spring Boot 3.x对应springdoc 2.x系列
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.14</version> </dependency>
5. 处理网关代理场景
若应用部署在API网关后,需确保网关转发所有Swagger相关资源请求(包括/swagger-ui/**、/v3/api-docs等),同时保留原始请求的Host头,避免Swagger无法正确推断Base URL。
内容的提问来源于stack exchange,提问作者virot

