SpringBoot整合Knife4j展示更美觀的API文檔


SpringBoot整合Knife4j展示更美觀的API文檔

 

一、什么是knife4j

knife4j是為Java MVC框架集成Swagger生成Api文檔的增強解決方案,前身是swagger-bootstrap-ui, 可以簡單理解為它是Swagger的一個UI增強版,該UI增強包主要包括兩大核心功能:文檔說明 和 在線調試;

  • 文檔說明:根據Swagger的規范說明,詳細列出接口文檔的說明,包括接口地址、類型、請求示例、請求參數、響應示例、響應參數、響應碼等信息,使用swagger-bootstrap-ui能根據該文檔說明,對該接口的使用情況一目了然。

  • 在線調試:提供在線接口聯調的強大功能,自動解析當前接口參數,同時包含表單驗證,調用參數可返回接口響應內容、headers、Curl請求命令實例、響應時間、響應狀態碼等信息,幫助開發者在線調試,而不必通過其他測試工具測試接口是否正確,簡介、強大。

二、整合試用

1. 創建一個普通SpringBoot項目

pom.xml依賴如下:

只需要引入一個依賴即可:<artifactId>knife4j-spring-boot-starter</artifactId> 

項目結構如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.linwei.knife4j.demo</groupId>
    <artifactId>knife4j-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>knife4j-demo</name>
    <description>Demo project for knife4j</description>
    <properties>
        <java.version>1.8</java.version>
        <knife4j.version>2.0.2</knife4j.version>
        <fastjson.version>1.2.68</fastjson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--knife4j依賴-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>${knife4j.version}</version>
        </dependency>

        <!-- fastJson(used for serialization of DAG) -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

2. 和以前Swagger一樣,添加一個配置類;

package com.linwei.knife4j.demo.cofig;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author: Linwei
 * @date 2021/6/15
 * @Description:
 * 配置類和以前使用swagger幾乎是一樣;
 * 注解比原來的swagger多加一個 @EnableSwaggerBootstrapUi
 */

@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //分組名稱
                .groupName("1.0版本")
                .select()
                //這里指定Controller掃描包路徑(項目路徑也行)
                .apis(RequestHandlerSelectors.basePackage("com.linwei.knife4j.demo.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XXX項目API接口文檔")
                .description("API服務相關接口")
                .termsOfServiceUrl("http://localhost:8888/")
                .contact(new Contact("Linwei",null,"Linwei.Lu@123456.com"))
                .version("1.0")
                .build();
    }
}

3. 准備測試實體和Controller

3.1 定義一個接口通用的返回對象 CommonResults 
package com.linwei.knife4j.demo.com.linwei.knife4j.demo.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Tolerate;

/**
 * @author: Linwei
 * @date 2021/6/15
 * @Description: 通用接口返回對象
 */

@Data
@Builder
@AllArgsConstructor
@ApiModel("接口通用返回對象")
public class CommonResults<T> {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(required = true,notes = "結果碼", example = "200")
    private int code;
    @ApiModelProperty(required = true,notes = "返回信息", example = "Success")
    private String message;
    @ApiModelProperty(required = false,notes = "返回數據", example = "{\"name:\":\"Jack\"}")
    private T data;

    @Tolerate
    public CommonResults() {
    }

    public static CommonResults ok() {
        return CommonResults.builder().code(200).message("請求成功").build();
    }

    public static CommonResults ok(Object data) {
        return CommonResults.builder().code(200).message("請求成功").data(data).build();
    }

    public static CommonResults error(String message) {
        return CommonResults.builder().code(500).message("響應異常").build();
    }
}
3.2 定義一個測試實體-UserEntity
package com.linwei.knife4j.demo.com.linwei.knife4j.demo.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author: Linwei
 * @date 2021/6/15
 * @Description:
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("用戶對象模型")
public class UserEntity {
    @ApiModelProperty(value="姓名" ,required= true,example = "Tom")
    private String name;
    @ApiModelProperty(value="年齡" ,required= true,example = "18")
    private Integer age;
    @ApiModelProperty(value="id" ,required= true,example = "123456")
    private Integer id;
}
3.3 添加一個controller來測試
package com.linwei.knife4j.demo.controller;

import com.linwei.knife4j.demo.com.linwei.knife4j.demo.entity.CommonResults;
import com.linwei.knife4j.demo.com.linwei.knife4j.demo.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @author: Linwei
 * @date 2021/6/15
 * @Description:
 */

@RestController
@RequestMapping("/user")
@Api("用戶接口")
public class UserController {

    @GetMapping("/getbyid")
    @ApiOperation("根據id獲取用戶信息接口")
    public CommonResults getUser(@RequestParam Integer id){
        UserEntity user = new UserEntity("Jerry",10,1111);
        return CommonResults.ok(user);
    }

    @PostMapping("/user/add")
    @ApiOperation(value = "添加用戶接口",notes = "入參是復雜對象", produces = "application/json")
    public CommonResults addUser(@RequestBody UserEntity user) {
        // 調用service保持用戶

        return CommonResults.ok();
    }

}
3.4 啟動springboot應用

 

 

4. API文檔查看

打開地址:http://localhost:8888/doc.html

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM