Knife4j文档增强工具使用

256 阅读1分钟

1、Knife4j 介绍:

  • 项目介绍文档 doc.xiaominfo.com/v2/document…
  • Knife4j是一个集Swagger2 和 OpenAPI3 为一体的增强解决方案
  • 取名knife4j是希望她能像一把匕首一样小巧,轻量,并且功能强悍,更名也是希望把她做成一个为Swagger接口文档服务的通用性解决方案,不仅仅只是专注于前端Ui前端

2、在maven项目的pom.xml中引入Knife4j的依赖包,代码如下:

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>```
    <version>2.0.8</version>
</dependency>

3、创建Swagger配置依赖,代码如下:

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {

    @Bean
    public Docket adminApiConfig(){
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("token")
                .description("用户token")
                .defaultValue("")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        pars.add(tokenPar.build());
        //添加head参数end

        //指定使用Swagger2规范
        Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
                //分组名称
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.loong"))
                //只显示/admin路径下的页面
                .paths(PathSelectors.regex("/admin/.*"))
                .build()
                .globalOperationParameters(pars);
        return adminApi;
    }

    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("后台管理系统-API文档")
                .description("本文档描述了后台管理系统微服务接口定义")
                .version("1.0")
                .contact(new Contact("loong", "http://www.baidu.com", "123456@qq.com"))
                .build();
    }
}

4、使用:

在类上在添加:
@Api(tags = "用户管理接口")
在方法上在添加:
@ApiOperation("查询所有用户列表")

5、启动Spring Boot项目,浏览器访问Knife4j的文档地址即可查看效果

访问地址:http://localhost:${port}/${context-path}/doc.html
例如:http://localhost:8345/doc.html#/home

6、参考地址