Spring Boot項目集成Knife4j接口文檔的實例代碼

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 = "[email protected]";

        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

image-20211220150948199

是因為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 = "[email protected]";

        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接口文檔內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: