swagger+knife4j記錄

niewj發表於2022-12-22

1. pom.xml

<?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.2.2.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>cn.itcast</groupId>
    <artifactId>knife4j_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

2.application.yml

server:
  port: 8081
niewj:
  swagger:
    enabled: true #是否啟用swagger
    base-package: com.niewj.controller
#    docket:
#      user:
#        title: 使用者模組
#        base-package: com.niewj.controller.user
#      menu:
#        title: 選單模組
#        base-package: com.niewj.controller.menu

3. 配置讀取屬性類SwaggerProperties

package com.niewj.config;

import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/*
*配置屬性類,用於封裝介面文件相關屬性,從配置檔案讀取資訊封裝成當前物件
*/

@Data
@ConfigurationProperties(prefix = "niewj.swagger")
public class SwaggerProperties {
    private String title = "線上文件"; //標題
    private String group = ""; //自定義組名
    private String description = "線上文件"; //描述
    private String version = "1.0"; //版本
    private Contact contact = new Contact(); //聯絡人
    private String basePackage = "com.niewj"; //swagger會解析的包路徑
    private List<String> basePath = new ArrayList<>(); //swagger會解析的url規則
    private List<String> excludePath = new ArrayList<>();//在basePath基礎上需要排除的url規則
    private Map<String, DocketInfo> docket = new LinkedHashMap<>(); //分組文件
    public String getGroup() {
        if (group == null || "".equals(group)) {
            return title;
        }
        return group;
    }
    @Data
    public static class DocketInfo {
        private String title = "線上文件"; //標題
        private String group = ""; //自定義組名
        private String description = "線上文件"; //描述
        private String version = "1.0"; //版本
        private Contact contact = new Contact(); //聯絡人
        private String basePackage = ""; //swagger會解析的包路徑
        private List<String> basePath = new ArrayList<>(); //swagger會解析的url規則
        private List<String> excludePath = new ArrayList<>();//在basePath基礎上需要排除的url
        public String getGroup() {
            if (group == null || "".equals(group)) {
                return title;
            }
            return group;
        }
    }
    @Data
    public static class Contact {
        private String name = "niewj"; //聯絡人
        private String url = ""; //聯絡人url
        private String email = ""; //聯絡人email
    }
}

4. SwaggerConfig

package com.niewj.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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;

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

@Configuration
@ConditionalOnProperty(name = "niewj.swagger.enabled", havingValue = "true", matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig implements BeanFactoryAware {
    @Autowired
    SwaggerProperties swaggerProperties;
    private BeanFactory beanFactory;

    @Bean
    @ConditionalOnMissingBean
    public List<Docket> createRestApi() {
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
        List<Docket> docketList = new LinkedList<>();
        // 沒有分組
        if (swaggerProperties.getDocket().isEmpty()) {
            Docket docket = createDocket(swaggerProperties);
            configurableBeanFactory.registerSingleton(swaggerProperties.getTitle(), docket);
            docketList.add(docket);
            return docketList;
        }
        // 分組建立
        for (String groupName : swaggerProperties.getDocket().keySet()) {
            SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);
            ApiInfo apiInfo = new ApiInfoBuilder()
                    //頁面標題
                    .title(docketInfo.getTitle())
                    //建立人
                    .contact(new Contact(docketInfo.getContact().getName(),
                            docketInfo.getContact().getUrl(),
                            docketInfo.getContact().getEmail()))
                    //版本號
                    .version(docketInfo.getVersion())
                    //描述
                    .description(docketInfo.getDescription())
                    .build();

            // base-path處理
            // 當沒有配置任何path的時候,解析/**
            if (docketInfo.getBasePath().isEmpty()) {
                docketInfo.getBasePath().add("/**");
            }
            List<Predicate<String>> basePath = new ArrayList<>();
            for (String path : docketInfo.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            // exclude-path處理
            List<Predicate<String>> excludePath = new ArrayList<>();
            for (String path : docketInfo.getExcludePath()) {
                excludePath.add(PathSelectors.ant(path));
            }

            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo)
                    .groupName(docketInfo.getGroup())
                    .select()
                    //為當前包路徑
                    .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                    .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                    .build();
            configurableBeanFactory.registerSingleton(groupName, docket);
            docketList.add(docket);
        }
        return docketList;
    }

    //構建 api文件的詳細資訊
    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                //頁面標題
                .title(swaggerProperties.getTitle())
                //建立人
                .contact(new Contact(swaggerProperties.getContact().getName(),
                        swaggerProperties.getContact().getUrl(),
                        swaggerProperties.getContact().getEmail()))
                //版本號
                .version(swaggerProperties.getVersion())
                //描述
                .description(swaggerProperties.getDescription())
                .build();
    }

    //建立介面文件物件
    private Docket createDocket(SwaggerProperties swaggerProperties) {
        //API 基礎資訊
        ApiInfo apiInfo = apiInfo(swaggerProperties);

        // base-path處理
        // 當沒有配置任何path的時候,解析/**
        if (swaggerProperties.getBasePath().isEmpty()) {
            swaggerProperties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        for (String path : swaggerProperties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path處理
        List<Predicate<String>> excludePath = new ArrayList<>();
        for (String path : swaggerProperties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .groupName(swaggerProperties.getGroup())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

5. 業務相關類

5.1 返回結果格式封裝Result

package com.niewj.common.response;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;

/**
 * 返回結果格式封裝
 *
 * @author nieweijun
 * @since 2021/6/29 18:43
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
@ApiModel(description = "返回結果資料封裝")
public class Result<T> {

    @ApiModelProperty(value = "返回結果code碼")
    private Integer code;
    @ApiModelProperty(value = "返回結果資訊描述")
    private String msg;
    @ApiModelProperty(value = "返回資料成功標識")
    private Boolean success;
    @ApiModelProperty(value = "返回資料詳情")
    private T data;

    /**
     * 用列舉來構造
     *
     * @param responseEnum 使用列舉值的code和msg填充Result
     * @param data         資料物件
     * @param ifSuccess    是否請求成功
     */
    public Result(ResponseEnum responseEnum, T data, Boolean ifSuccess) {
        this.setCode(responseEnum.getCode());
        this.setMsg(responseEnum.getMsg());
        this.setData(data);
        this.setSuccess(ifSuccess);
    }

    /**
     * success={"code":200,"msg":"成功","data":"xxx","success":true}
     *
     * @param data
     * @return
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), Boolean.TRUE, data);
    }

    /**
     * success={"code":200,"msg":"成功","data": null,"success":true}
     *
     * @return
     */
    public static <T> Result<T> successWithNull() {
        return new Result<>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), Boolean.TRUE, null);
    }

    /**
     * success={"code":200,"msg":"成功","data": [],"success":true}
     *
     * @return
     */
    public static <T> Result<T> successWithEmptyList() {
        return (Result<T>) Result.success(new ArrayList<T>());
    }

    /**
     * success=除了返回true指定, 其他的都由引數指定
     *
     * @param code
     * @param msg
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(Integer code, String msg, T data) {
        return new Result<>(code, msg, Boolean.TRUE, data);
    }

    /**
     * success等價於new Result(ResponseEnum, T, true)
     *
     * @param responseEnum
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(ResponseEnum responseEnum, T data) {
        return new Result<>(responseEnum, data, Boolean.TRUE);
    }

    /**
     * fail-除了返回false, 其他的引數指定
     * 例如: {"code":xxx,"msg":"xxx", "data": "指定的錯誤", "success":false}
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(Integer code, String msg, T data) {
        return new Result<>(code, msg, Boolean.FALSE, data);
    }

    /**
     * fail-除了返回false, 其他的引數指定-由列舉類指定
     * 例如: {"code":xxx,"msg":"xxx", "data": "指定的錯誤", "success":false}
     *
     * @param responseEnum
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(ResponseEnum responseEnum, T data) {
        return new Result<>(responseEnum.getCode(), responseEnum.getMsg(), Boolean.FALSE, data);
    }

}

5.2 響應列舉

package com.niewj.common.response;

/**
 * 響應列舉:code和message的封裝(注意: code宣告為int方便比較; Integer的話需要equals!)
 *
 * @author nieweijun
 * @since 2021/6/29 18:51
 */
public enum ResponseEnum {

    SUCCESS(200, "成功"),
    REPEAT(201, "重複操作"),
    BAD_REQUEST(400, "請求引數不合規"),
    ERROR(500, "伺服器異常"),
    RPC_ERROR(501, "RPC伺服器異常"),

    //=========================業務編碼=========================
    NO_LOGIN(1001, "未登入"),
    RISK(1002, "系統繁忙"),
    RECODE_REPEAT(1003, "有重複資料"),
    DATA_LACK(1004, "請求資料缺失或超時"),
    NO_PERMISSION(1005, "使用者無許可權"),

    // ========================RPC服務問題========================
    RPC_INVOKE_ERROR(2001, "依賴服務發生異常"),
    RPC_DATA_INVALID(2002, "依賴服務資料無效"),
    RPC_INVOKE_TIMEOUT(2003, "依賴服務請求超時"),
    UNDER_REVIEW(2004, "預計10分鐘內稽核完畢,請稍後再重新進入小程式"),

    RPC_DISASSEMBLY_FAIL(2008, "提交舊機拆解失敗"),

    OTHER(-1, "其他");

    // 宣告為簡單型別是為了方便用==比較;
    // 200 == Integer(200) ->true
    // 200 == 200 -> true
    // Integer(200) == Integer(200) -> false
    private int code;
    private String msg;

    ResponseEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public int getCode() {
        return code;
    }

    public static ResponseEnum getByCode(int code) {
        for (ResponseEnum responseCode : ResponseEnum.values()) {
            if (responseCode.getCode() == code) {
                return responseCode;
            }
        }
        return ERROR;
    }

}

5.3 model-1: Menu

package com.niewj.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
@ApiModel(description = "選單實體")
public class Menu {
    @ApiModelProperty(value = "主鍵")
    private int id;
    @ApiModelProperty(value = "選單名稱")
    private String name;
}

5.3 model-2: User

package com.niewj.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
@ApiModel(description = "使用者實體")
public class User {
    @ApiModelProperty(value = "主鍵")
    private int id;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "年齡")
    private int age;
    @ApiModelProperty(value = "地址")
    private String address;
}

5.4 MenuController

package com.niewj.controller;

import com.niewj.common.response.Result;
import com.niewj.model.Menu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/menu")
@Api(tags = "選單控制器")
@Slf4j
public class MenuController {

    @GetMapping("/getMenus")
    @ApiOperation(value = "查詢所有選單", notes = "查詢所有選單資訊")
    public Result<List<Menu>> getMenus() {
        log.info("getMenus success!");

        List<Menu> list = new ArrayList<>();
        list.add(new Menu(100, "menu100"));
        list.add(new Menu(101, "menu101"));
        list.add(new Menu(102, "menu102"));
        return Result.success(list);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增選單", notes = "新增選單資訊")
    public Result<Boolean> save(@RequestBody Menu menu) {
        log.info("save success!");

        return Result.success(Boolean.TRUE);
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改選單", notes = "修改選單資訊")
    public Result<Boolean> update(@RequestBody Menu menu) {
        log.info("update success!");

        return Result.success(Boolean.TRUE);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "刪除選單", notes = "刪除選單資訊")
    public Result<Boolean> delete(int id) {
        log.info("update success!");

        return Result.success(Boolean.TRUE);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "頁碼", required = true, type = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每頁條數", required = true, type = "Integer"),
    })
    @ApiOperation(value = "分頁查詢選單資訊")
    @GetMapping(value = "page/{pageNum}/{pageSize}")
    public String findByPage(@PathVariable Integer pageNum,
                             @PathVariable Integer pageSize) {

        List<Menu> list = new ArrayList<>();
        list.add(new Menu(100, "menu100"));
        list.add(new Menu(101, "menu101"));
        list.add(new Menu(102, "menu102"));

        return "OK";
    }
}

5.5 UserController

package com.niewj.controller;

import com.niewj.common.response.Result;
import com.niewj.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/user")
@Api(tags = "使用者控制器")
public class UserController {
    @GetMapping("/getUsers")
    @ApiOperation(value = "查詢所有使用者", notes = "查詢所有使用者資訊")
    public Result<List<User>> getAllUsers() {
        List<User> list = new ArrayList<>();
        list.add(new User(100, "小0", 20, "北京"));
        list.add(new User(101, "小1", 30, "北京"));
        list.add(new User(102, "小2", 23, "西安"));
        return Result.success(list);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增使用者", notes = "新增使用者資訊")
    public Result<Boolean> save(@RequestBody User user) {
        return Result.success(Boolean.TRUE);
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改使用者", notes = "修改使用者資訊")
    public Result<Boolean> update(@RequestBody User user) {
        return Result.success(Boolean.TRUE);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "刪除使用者", notes = "刪除使用者資訊")
    public Result<Boolean> delete(int id) {
        return Result.success(Boolean.TRUE);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "頁碼", required = true, type = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每頁條數", required = true, type = "Integer"),
    })
    @ApiOperation(value = "分頁查詢使用者資訊")
    @GetMapping(value = "page/{pageNum}/{pageSize}")
    public Result<List<User>> findByPage(@PathVariable Integer pageNum,
                                         @PathVariable Integer pageSize) {
        List<User> list = new ArrayList<>();
        list.add(new User(100, "小0", 20, "北京"));
        list.add(new User(101, "小1", 30, "北京"));
        list.add(new User(102, "小2", 23, "西安"));
        return Result.success(list);
    }
}

5.6 啟動類

package com.niewj;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

5.7 啟動後訪問

訪問地址: http://localhost:8081/doc.html
即可