Swagger 2.7.0报错Unable to infer base url,求解决方案
Swagger 2.7.0「无法推断基础URL」问题排查与解决
我在使用Swagger 2.7.0生成API文档时,遇到「Unable to infer base url」(无法推断基础URL)错误,手动输入
http://localhost:8080/仍未解决。具体提示翻译如下:
无法推断基础URL。这种情况常见于使用动态Servlet注册或API位于API网关之后。基础URL是所有Swagger资源的服务根路径。例如,如果API可通过http://example.org/api/v2/api-docs访问,那么基础URL是http://example.org/api/。请手动输入位置:
当前配置信息
依赖配置
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
SwaggerConfig配置
@EnableSwagger2 public class SwaggerConfig { @Bean public Docket apiDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.javaspring.blogapi")) .paths(PathSelectors.any()) .build(); } }
SecurityConfig相关配置
http.authorizeHttpRequests(auth -> auth .requestMatchers("/api/v1/auth/**", "/v2/api-docs", "/v3/api-docs", "/v3/api-docs/**", "/swagger-resources", "/swagger-resources/**", "/configuration/ui", "/configuration/security", "/swagger-ui/**", "/webjars/**", "/swagger-ui.html").permitAll()
控制器示例
@RestController @RequestMapping(path = "/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{username}") public ResponseEntity<UserDTO> getUser(@PathVariable String username){ return ResponseEntity.ok().body(userService.findByUsername(username)); } }
解决方案排查
1. 确保SwaggerConfig被Spring加载
给SwaggerConfig添加@Configuration注解,保证Spring能扫描并初始化这个配置类:
@Configuration @EnableSwagger2 public class SwaggerConfig { // ... 原有代码保持不变 }
2. 修正SecurityConfig的路径匹配
- 先修正代码笔误:把lambda里的
Auth改成参数auth - 针对Swagger 2.7.0,移除不需要的
/v3/api-docs相关路径,保留对应版本的资源路径:
http.authorizeHttpRequests(auth -> auth.requestMatchers("/api/v1/auth/**", "/v2/api-docs", "/swagger-resources", "/swagger-resources/**", "/configuration/ui", "/configuration/security", "/swagger-ui.html", "/webjars/**") .permitAll() .anyRequest().authenticated());
- 如果用的是Spring Boot 2.6及以上版本,在
application.properties中添加配置关闭路径匹配严格模式:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
3. 显式配置Swagger基础URL
在SwaggerConfig中直接指定服务地址和根路径,避免自动推断失败:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket apiDocket() { return new Docket(DocumentationType.SWAGGER_2) .host("localhost:8080") .select() .apis(RequestHandlerSelectors.basePackage("com.javaspring.blogapi")) .paths(PathSelectors.any()) .build() .pathMapping("/"); } }
4. 检查应用上下文路径
如果应用配置了自定义上下文路径(比如server.servlet.context-path=/api),手动输入基础URL时必须带上这个前缀(比如http://localhost:8080/api/),同时确保SecurityConfig中的路径匹配包含该前缀或者用通配符覆盖。
内容的提问来源于stack exchange,提问作者NqanVo
相关产品推荐
相关产品推荐

