springboot2.x使用 swagger2不同版本所带来的问题

1、swagger2:2.9.x 以下版本

在springboot2.x 项目中只需要加入一下配置代码即可
引入包,我是用的gradle,Maven同理

    // swagger
    implementation 'io.springfox:springfox-swagger2:2.9.2'
    // swagger ui
    implementation 'io.springfox:springfox-swagger-ui:2.9.2'

配置

@Configuration
@EnableSwagger2
public class Swagger2Config  {


    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2);
               
    }

启动项目后,例如端口是8090,直接访问:http://localhost:8090/swagger-ui.html,效果如下:
在这里插入图片描述
不需要其他的配置项,即可成功运行。

2、swagger2:2.10.5

配置代码同上,只是@EnableSwagger2注解变成了@EnableSwagger2WebMvc,同时需要多引入一个包:springfox-spring-webmvc。
引入包

 // swagger
    implementation 'io.springfox:springfox-swagger2:2.10.5'
    // swagger ui
    implementation 'io.springfox:springfox-swagger-ui:2.10.5'
    // 注意:必须引入此包
    **implementation 'io.springfox:springfox-spring-webmvc:2.10.5'**

若不引入springfox-spring-webmvc:2.10.5,访问时,会弹出一个错误窗口,如下图:
在这里插入图片描述

3、swagger2:3.0.0

引入包

    // swagger
    implementation 'io.springfox:springfox-swagger2:3.0.0'
    // swagger ui
    implementation 'io.springfox:springfox-swagger-ui:3.0.0'

配置同第一个,@EnableSwagger2又回来啦,但是访问是404,如下图:
在这里插入图片描述
解决方式:
加入webConfig配置

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger配置 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

在这里插入图片描述
注意:请求地址是http://localhost:8090//swagger-ui/index.html,与旧版本不同。

4、swagger2:3.0.0更优方式

直接引入包

implementation 'io.springfox:springfox-boot-starter:3.0.0'

不需要加任何配置,便可使用了,非常的方便。并且Swagger2Config中可以去掉@EnableSwagger2注解。

5、更漂亮的ui界面,集成swagger-bootstrap-ui

在swagger2:3.0.0的基础上,引入包

implementation 'com.github.xiaoymin:swagger-bootstrap-ui:1.9.6'

访问地址:http://localhost:8090/doc.html,即可看到更好看的ui界面了,注意访问地址是doc.html。如下图:
在这里插入图片描述

6、更漂亮的UI界面2,集成knife4j

最新版knife4j已经集成了swagger2的包,只需引入knife4j包

 implementation 'com.github.xiaoymin:knife4j-spring-boot-starter:3.0.3'

访问地址:http://localhost:8090/doc.html,效果如下图:
在这里插入图片描述
最新版:官方:https://doc.xiaominfo.com/docs/quick-start
在这里插入图片描述
试了试最新版本的引入,项目未做任何配置修改

implementation 'com.github.xiaoymin:knife4j-openapi2-spring-boot-starter:4.5.0'

结果出错了:
在这里插入图片描述
原因是没有在配置文件导入配置信息:
在yml中加入:

knife4j

knife4j:

是否开启

enable: true
需要开启
效果图如下:
在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值