SpringBoot 集成 knife4j (Swagger2)

📅 2021-12-09 17:47 👁️ 873 💬 0

SpringBoot 集成 knife4j (Swagger2)

前提 :本文 spring boot版本为 2.6.1 ,knife4j 版本为:3.0.3

1、初始化项目,导入pom依赖

<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

2、创建Swagger配置类

@Configuration
public class Swagger2Config {



    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                // 这里可以指定扫描包的路径 或者 扫描指定的注解
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build().protocols(this.newHashSet("https","http"));
    }

    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        return ts.length > 0 ? new LinkedHashSet(Arrays.asList(ts)) : null;
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger接口文档")
                .description("文档描述")
                .contact( new Contact("xmStudy","https://www.cnblogs.com/XiaoMingStudy1/","123@qq.com"))
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

}

最终项目结构图如下:

image-20211209181859354

3、出现的问题

项目启动失败

image-20211209145058757

4、解决问题

原因分析:在springboot 2.6.0会提示documentationPluginsBootstrapper NullPointerException,具体位置的WebMvcPatternsRequestConditionWrapper中的condition为null。原因是在springboot2.6.0中将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错,解决办法是切换会原先的AntPathMatcher

解决问题:在properties中加上spring.mvc.pathmatch.matching-strategy=ant-path-matcher

5、项目正常启动,访问一下

ip为 ip:port/doc.html, 如 http://localhost:8080/doc.html#/home

image-20211209181922447

6 参考连接

  1. Knife4j 官方文档:https://doc.xiaominfo.com/knife4j/
  2. Github地址:https://github.com/xiaoymin/swagger-bootstrap-ui/issues/396
  3. Gitee地址:https://toscode.gitee.com/xiaoym/knife4j
登录后才能查看或发表评论, 立即 登录
点击右上角即可分享
微信分享提示