SpringBoot集成Swagger3.0

  1. pom.xml

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>3.0.0</version>
    </dependency>
    
  2. SwaggerConfig

    /**
     * @author: zek
     * @desc: swagger
     */
    @EnableOpenApi
    @Configuration
    public class SwaggerConfig implements WebMvcConfigurer {
         
      @Bean
      public Docket createRestApi() {
         
        return new Docket(DocumentationType.OAS_30)
            .pathMapping("/")
            // 定义是否开启swagger,false为关闭,可以通过变量控制
            .enable(true)
            // 将api的元信息设置为包含在json ResourceListing响应中。
            .apiInfo(apiInfo())
            // 接口调试地址
            .host("http://localhost:8080")
            // 选择哪些接口作为swagger的doc发布
            .select()
            .apis(RequestHandlerSelectors.basePackage("xx.xx.xx.controller"))
            .paths
### SpringBoot集成Swagger3.0访问路径404解决方案 在Spring Boot项目中集成Swagger3.0时,如果遇到访问路径返回404错误的情况,可能是由于以下几个原因引起的: #### 1. **版本兼容性问题** 从Spring Boot 2.6.0开始,默认使用`PathPatternParser`作为路径匹配器,而Swagger的旧版依赖仍然基于`AntPathMatcher`。这种不一致可能导致某些路径无法正常解析[^2]。 解决方法是在项目的`application.yml`文件中禁用新的路径模式解析器并恢复到传统的`AntPathMatcher`方式: ```yaml spring: mvc: pathmatch: matching-strategy: ant_path_matcher ``` #### 2. **引入正确的依赖** 确保项目中的Maven或Gradle配置包含了最新的Swagger支持库。对于Swagger3.0及以上版本,推荐使用以下依赖项[^1][^3]: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 注意:如果仅引入上述依赖仍无法解决问题,则可能需要额外添加Knife4j插件来增强功能和支持更复杂的场景[^4]。 #### 3. **正确设置启动类上的注解** 根据所使用的Swagger具体版本调整应用主程序入口处的相关注解定义: - 对于低于3.0.0版本应标注为`@EnableSwagger2`; - 而等于或者高于此界限则替换成为`@EnableOpenApi`. 例如,在SpringBootApplication上加上如下声明即可完成初始化工作: ```java import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableOpenApi // For Swagger 3.x versions. public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` #### 4. **确认资源映射地址无误** 随着Swagger迭代升级其默认UI页面位置也有所改变: - 版本号小于3.0.0时通过浏览器打开链接形如 `http://localhost:<port>/swagger-ui.html`. - 大于等于该临界点后需改访另一形式即 `http://localhost:<port>/swagger-ui/index.html#/` 或者简化后的 `/swagger-ui/`. 因此当发现请求失败提示找不到目标文件夹时候可以先核实当前安装包实际对应哪一类情况再做相应修改尝试重新加载网页查看效果如何. #### 示例代码片段展示完整流程 下面给出一段综合性的实现样例供参考学习之用: ```java @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } } ``` --- ###
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值