Knife4j就相当于是swagger的升级版,对于我来说,它比swagger要好用得多

1、在pom.xml引入依赖包

<!-- Swagger配置依赖knife4j -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.9</version>
</dependency>

2、创建Knife4j配置文件

package com.yuyun.config;

import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hyh
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                // 是否启用Swagger
                .enable(true)
                //分组名称
                .groupName("1.0版本")
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //指定Controller扫描包路径
//                .apis(RequestHandlerSelectors.basePackage("com.yuyun.controller"))
                // 扫描所有
//                .apis(RequestHandlerSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {

        String name = "雨云";
        String url = "https://www.xxx.com/";
        String email = "1873591403@qq.com";

        Contact contact = new Contact(name, url, email);

        return new ApiInfoBuilder()
                .title("API接口文档")
                .description("API接口文档描述")
                .termsOfServiceUrl("https://www.xx.com/")
                .contact(contact)
                .version("1.0.1")
                .build();
    }
}

注意:如果出现错误Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

是因为SpringBoot版本高了,将版本降下去或者在application.yml添加如下内容即可解决该错误

spring: 
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

项目运行后,访问ip+端口号+/doc.html,比如http://localhost:8110/doc.html。效果如图

3、使用Knife4j注解

(1)在实体类中使用

@ApiModel 放在在响应实体类上,用于描述该类

@ApiModelProperty 描述该响应类的属性

/**
 * 企业信息表
 *
 * @author  
 * @since 1.0.0 2021-12-17
 */
@Data
@ApiModel(value = "企业信息表")
@TableName("company")
public class CompanyDTO implements Serializable {
    private static final long serialVersionUID = 1L;

	/**
	 * 主键
	 */
	@ApiModelProperty(value = "主键")
	private Long id;

	/**
	 * 企业名称
	 */
	@ApiModelProperty(value = "企业名称")
	private String companyName;

	/**
	 * 简介
	 */
	@ApiModelProperty(value = "简介")
	private String description;
}

(2)在Controller层使用

@RestController
@RequestMapping("company")
@Api(tags = "企业信息表")
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    @GetMapping("getList")
    @ApiOperation("根据条件获取数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "名称", paramType = "query", required = true, dataType = "String")
    })
    public Result<List<CompanyDTO>> getList(@ApiParam(name = "address", value = "地址", required = true)  String address) {
        List<CompanyDTO> companyList = companyService.list();

        return new Result<List<CompanyDTO>>().success(companyList);
    }
}

还有其他一些注解,用到再了解

4、全局参数

在实际项目中访问接口都添加了权限,每次访问都要带一个请求头参数token。全局参数就是为了方便传一个固定的参数。当添加全局参数后,所有的接口都会带上该参数。

第一种

在配置文件中加入

private List<SecurityScheme> securitySchemes() {
    List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
    apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
    return apiKeyList;
}

defaultApi2()方法内引用

.securitySchemes(securitySchemes())

最后配置文件中的内容:

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                // 是否启用Swagger
                .enable(true)
                //分组名称
                .groupName("1.0版本")
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //指定Controller扫描包路径
//                .apis(RequestHandlerSelectors.basePackage("com.yuyun.controller"))
                // 扫描所有
//                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                /* 设置安全模式,swagger可以设置访问token */
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .pathMapping("/");
        return docket;
    }

    private ApiInfo apiInfo() {

        String name = "雨云";
        String url = "https://www.xxx.com/";
        String email = "1873591403@qq.com";

        Contact contact = new Contact(name, url, email);

        return new ApiInfoBuilder()
                .title("API接口文档")
                .description("API接口文档描述")
                .termsOfServiceUrl("https://www.xx.com/")
                .contact(contact)
                .version("1.0.1")
                .build();
    }

    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

}

效果:菜单上多了一个Authorize,在参数值中添加上信息

刷新一下,再打开接口就会发现多了个请求头部

第二种

直接在菜单文档管理全局参数设置,然后添加参数:

再打开接口就会发现请求头参数加上了


源码地址:https://gitee.com/hyh17808770899/spring-boot/tree/master/springboot-03

到此这篇关于Spring Boot项目集成Knife4j接口文档的文章就介绍到这了,更多相关Spring Boot集成Knife4j接口文档内容请搜索悠悠之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠悠之家!

点赞(159)

评论列表共有 0 条评论

立即
投稿
返回
顶部