SpringBoot使用Swagger2出现404

作者在开发微服务项目时遇到Swagger2接口访问返回404,问题源于在pom.xml文件中设置了两个相同的parent标签,导致依赖出现问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在写微服务项目的时候遇到访问swagger2一直出现404的情况,经过排查发现:

如果加上了这行代码

<relativePath>../../pom.xml</relativePath>

 那么依赖就会出现问题,导致404。

<parent>
        <groupId>com.eds</groupId>
        <artifactId>education_system</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
</parent>
<parent>
        <groupId>com.eds</groupId>
        <artifactId>education_system</artifactId>
        <version>0.0.1-SNAPSHOT</version>
</parent>
### 解决 Spring Boot 集成 Swagger2 出现 404 错误的方法 当遇到 Spring Boot 应用程序集成 Swagger2 后访问接口文档返回 404 的情况时,可能的原因及对应的解决方案如下: #### 1. 路径匹配策略调整 对于某些高版本的 Spring Boot (如 2.6 及以上),默认路径匹配机制有所变化,这可能导致 Swagger UI 页面无法正常加载。可以在 `application.yml` 文件中指定使用旧版路径匹配器来解决问题。 ```yaml spring: mvc: pathmatch: matching-strategy: ant_path_matcher ``` 此设置确保了与早期版本兼容性[^2]。 #### 2. 添加必要的依赖项 确认 pom.xml 中包含了正确的 Swagger 和其他所需库的依赖声明。以下是适用于 Spring Boot 2.x 和 Swagger2 2.9.x 组合的一个典型配置片段: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 这些条目保证了应用程序能够识别并处理来自 Swagger 的请求[^4]。 #### 3. 正确启用 Swagger 功能 在主类或任意配置类上添加 `@EnableSwagger2` 注解以激活 Swagger 支持功能。此外,还需定义 Docket Bean 来定制 API 文档的具体行为。 ```java import org.springframework.context.annotation.Bean; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 这段代码使得所有控制器中的方法都被纳入到自动生成的 API 文档之中[^3]。 #### 4. 访问 URL 地址校验 最后需要注意的是,在浏览器地址栏输入正确的 URL 才能成功打开 Swagger UI 界面,默认情况下应该是类似于 http://localhost:{port}/swagger-ui.html 这样的形式(其中 `{port}` 是应用运行的实际端口号)。如果仍然显示 404,则需进一步排查是否存在防火墙阻止或其他网络层面的问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值