【Swagger】maven项目整合Swagger(含Springfox3.0与spring boot 2.6.0及以上版本冲突解决办法)

本文介绍了在Springfox3.0与Springboot2.6.0及以上版本存在匹配器冲突时的三种解决方案,包括在application.properties中配置路径匹配策略、启用@EnableWebMvc注解和降级SpringBoot版本。此外,文章详细展示了Swagger的配置步骤,包括引入依赖、配置类设置、Controller接口注解以及如何处理JWT认证和拦截器配置。最后,文章提醒读者在测试SwaggerUI时应注意的事项。

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

【Swagger】maven项目整合Swagger(含Springfox3.0与spring boot 2.6.0及以上版本冲突解决办法)

Swagger配置使用三步走战略

(1)引入Swagger依赖坐标(注意spring boot创建时的版本)

  <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.7.8</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>
   
  <!--Swagger文档工具-->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>3.0.0</version>
  </dependency>

需要着重注意一下springboot项目创建的版本问题:

springboot项目创建版本从 2.5.6 变成了 2.6.0用的是在线方式;
Spring Boot 2.6.0及以上版本使用的是PathPatternMatcher,而Springfox原使用的路径匹配是基于AntPathMatcher的。

解决方案有三,如下:

解决方案(1):
在application.properties里配置(在application.yml里的配置类似,注意换行):
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

解决方案(2):
在启动类 或 配置类 添加注解@EnableWebMvc(本文测试类使用,测试OK)

解决方案(3):
降低Spring Boot 版本,比如可以考虑将Spring Boot版本降低为2.5.6。如下:

  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.5.6</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

(2)Swagger配置类

@Configuration
@EnableOpenApi
@EnableWebMvc  //解决Springfox3.0与2.6.0及以上版本的冲突的问题
public class MySwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lantu"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("东方世纪教育管理系统接口文档")
                .description("大气--全网最简单的SpringBoot+Vue前后端分离项目实战")
                .version("1.0")
                .contact(new Contact("大气云泥", "http://www.daqi.cn", "daqi@aliyun.com"))
                .build();
    }
}

(3)在Controller层添加Swagger接口注解

@Api(tags = {"用户接口列表"})
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("查询所有用户")
    @GetMapping("/all")
    public List<User> findAllUser(){
        List<User> users = userService.list();
        return users;
    }
}    

(4)项目启动检验效果

访问swaggerUI界面 http://localhost:9999/swagger-ui/index.html

在这里插入图片描述

其实到这Swagger就算配置OK了。

下面是一些使用中遇到过的坑,也一并记录在这里,诸君大概看一下,或有参考的作用。

一些注意点:

(1)注意点-x1,如果项目里配置了WebMvcConfigurer的拦截器,需要开放Swagger请求端口。拦截器配置如下:

@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private JwtValidateInterceptor jwtValidateInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(jwtValidateInterceptor);
        registration.addPathPatterns("/**")  //拦截所有
                .excludePathPatterns(    //忽略请求
                        "/user/login",
                        "/user/logout",
                        "/user/info",
                        "/error",
                        "/swagger-ui/**",
                        "/swagger-resources/**",
                        "/v3/**"
                );
    }
}

(2)注意点-x2,如果项目配置了jwt拦截认证,这需要对Swagger授权配置才可以。如下:

jwt拦截认证细节可见另一篇文章 JwtUtil工具类与测试情况

@Configuration
@EnableOpenApi
@EnableWebMvc
public class MySwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lantu"))
                .paths(PathSelectors.any())
                .build()
                //Swagger授权配置-x4
                .securitySchemes(Collections.singletonList(securityScheme()))
                .securityContexts(Collections.singletonList(securityContext()));
    }

    //Swagger授权配置-x1 【在请求头里面自动携带用户传入的token】
    private SecurityScheme securityScheme() {
        //return new ApiKey("Authorization", "Authorization", "header");
        return new ApiKey("X-Token", "X-Token", "header");
    }
    //Swagger授权配置-x2
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$"))
                .build();
    }
    //Swagger授权配置-x3
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Collections.singletonList(
                new SecurityReference("X-Token", authorizationScopes));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("东方世纪教育管理系统接口文档")
                .description("大气--全网最简单的SpringBoot+Vue前后端分离项目实战")
                .version("1.0")
                .contact(new Contact("大气云泥", "http://www.daqi.cn", "daqi@aliyun.com"))
                .build();
    }
}

(3)再次测试需要注意的事项
访问swaggerUI界面 http://localhost:9999/swagger-ui/index.html

如下图:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

测试OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东方神剑2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值