Springboot2.3.12集成swagger2.10.5时出现的问题

150 阅读1分钟

我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情(juejin.cn/post/713863…)

啥是swagger

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。具有以下特色:

  • 及时性

接口变更后,能够及时准确地通知相关前后端开发人员

  • 规范性

保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息

  • 一致性

接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧

  • 可测性

直接在接口文档上进行测试,以方便理解业务

编写和维护接口文档是每个程序员的职责,根据Swagger2可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。

Springboot整合Swagger:

参考以下解决思路;

整合时出现问题如下:

在使用springboot集成swagger时提示如下图错误; 在这里插入图片描述

使用的版本如下: verSpringBoot = '2.3.12.RELEASE' verSpringFramework = '5.3.20' verSpringfox = '2.10.5'

其中Spingboot版本为2.3.12 Swagger版本为2.10.5 Spring版本是5.3.20

引入依赖

implementation "org.springframework.boot:spring-boot-starter-web:${verSpringBoot}"
implementation "org.springframework:spring-webmvc:${verSpringFramework}"
implementation "org.springframework:spring-aop:${verSpringFramework}"
implementation "org.springframework:spring-web:${verSpringFramework}"
implementation "org.springframework:spring-context:${verSpringFramework}"
implementation "org.springframework:spring-beans:${verSpringFramework}"
//swagger
implementation "io.springfox:springfox-swagger2:${verSpringfox}"
implementation "io.springfox:springfox-swagger-ui:${verSpringfox}"

编码swagger配置

需要使用的注解为EnableSwagger2WebMvc,因为在2.10版本。EnableSwagger2已经不可用; 使用这个注解是问题出现的原因;

@Configuration
@ComponentScan(basePackages = {
        "com.common.rs"
})
@EnableSwagger2WebMvc
public class SwaggerConfiguration {

    @Value("${swagger.enabled:true}")
    private Boolean enabled;

    @Bean
    public Docket docketCommon(){
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage("comcommon.rs"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder().
                        title("Restful API").
                        description("接口的API").
                        contact(new Contact("", "", "")).
                        version("1.0").
                        build());
    }
}

运行代码后,启动工程访问swager页面,出现以上问题;

问题解决

之前使用的是@EnableSwagger2,启动时不会有问题,改用了注解后,出现问题,考虑是注解问题; 经过搜索,发现在使用EnableSwagger2WebMvc注解时,需要依赖一个特殊的jar;

io.springfox:springfox-spring-webmvc

引入依赖:

implementation "io.springfox:springfox-swagger2:${verSpringfox}"
implementation "io.springfox:springfox-swagger-ui:${verSpringfox}"
implementation "io.springfox:springfox-spring-webmvc:${verSpringfox}"

重启服务,问题解决;