SpringBoot配置swagger-ui可視化接口文檔


1.引入依賴

<!--Swagger-ui 圖形化接口-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui ->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
 

2.添加配置類

import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// 啟動時加載類
@Configuration
// 啟用Swagger API文檔
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 自行修改為自己的包路徑
                .apis(RequestHandlerSelectors.basePackage("com.zp.springbootdemo.system.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("客戶管理")
                .description("客戶管理中心 API 1.0 操作文檔")
                .version("1.0")
                .build();
    }
}

 

3.Swagger常用注解

作用范圍 API 使用位置
協議集描述 @Api 用於 Controller 類上
協議描述 @ApiOperation 用在 Controller 的方法上
非對象參數集 @ApiImplicitParams 用在 Controller 的方法上
非對象參數描述 @ApiImplicitParam 用在 @ApiImplicitParams 的方法里邊
響應集 @ApiResponses 用在 Controller 的方法上
響應信息參數 @ApiResponse 用在 @ApiResponses 里邊
描述返回對象的意義 @ApiModel 用在返回對象類上
對象屬性 @ApiModelProperty 用在出入參數對象的字段上
@Api的使用
API作用在Controller,作為swagger文檔資源,該注解將一個controller標注為一個Swagger資源(API). 在默認情況下,Swagger-Core 只會掃描解析具有 @Api 注解的類,而會自動忽略其他類別資源(JAX-RS endpoints、Servlets 等)的注解。
@Api(value = "用戶信息",description = "用戶操作 API", position = 100, protocols = "http")
@RestController
@RequestMapping("/user")
public class UserController{
}

啟動項目,訪問http://localhost:8080/swagger-ui.html#/message-controller 就可以看到效果,自動將MessageController內的方法都添加映射,並標明了每種方法的請求方式

@ApiOperation 的使用

ApiOperation 定義在方法上,描述方法名、方法解釋、返回信息、標記等信息。

屬性名稱 備注
value url 的路徑值
tags 如果設置這個值,value 的值會被覆蓋
description 對 API 資源的描述
produces For example, "application/json, application/xml"
consumes For example, "application/json, application/xml"
protocols Possible values: http, https, ws, wss
authorizations 高級特性認證時配置
hidden 配置為 true 將在文檔中隱藏
response 返回的對象
responseContainer 這些對象是有效的 "List", "Set" or "Map",其他無效
httpMethod "GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS" and "PATCH"
code http 的狀態碼 默認 200
extensions 擴展屬性
@ApiOperation(value = "/獲取用戶信息",notes = "根據id獲取用戶信息",httpMethod = "POST")
    @PostMapping("/getUser")
    public JSONObject getUser(@RequestBody JSONObject user){
}

 

@ApiImplicitParams 和 @ApiImplicitParam 的使用

@ApiImplicitParams 用於描述方法的返回信息,和 @ApiImplicitParam 注解配合使用;@ApiImplicitParam 用來描述具體某一個參數的信息,包括參數的名稱、類型、限制等信息。

@ApiOperation(
        value = "添加信息",
        notes = "根據傳遞的參數創建信息"
)
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "消息ID", required = true, dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "text", value = "消息正文", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),

})
@PostMapping(value = "message")
public Message create(Message message) {
    message = this.messageRepository.save(message);
    return message;
}

  

屬性名稱 備注
name 接收參數名
value 接收參數的意義描述
required 參數是否必填值為 true 或者 false
dataType 參數的數據類型只作為標志說明,並沒有實際驗證
paramType 查詢參數類型,其值:
path 以地址的形式提交數據
query 直接跟參數完成自動映射賦
body 以流的形式提交,僅支持 POST
header 參數在 request headers 里邊提交
form 以 form 表單的形式提交 僅支持 POST
@ApiResponses 和 @ApiResponse 的使用

@ApiResponses 主要封裝方法的返回信息和 @ApiResponse 配置起來使用,@ApiResponse 定義返回的具體信息包括返回碼、返回信息等。

@ApiOperation(value = "修改信息", notes = "根據參數修改信息")
@ApiResponses({
        @ApiResponse(code = 100, message = "請求信息有誤"),
        @ApiResponse(code = 101, message = "未授權"),
        @ApiResponse(code = 103, message = "禁止訪問"),
        @ApiResponse(code = 104, message = "請求路徑不存在"),
        @ApiResponse(code = 200, message = "服務器內部錯誤"),
})
@PutMapping(value = "message")
public Message modify(Message message) {
    Message messageResult=this.messageRepository.update(message);
    return messageResult;
}
屬性名稱 備注
code http 的狀態碼
message 描述
response 默認響應類 Void
reference 參考
responseHeaders 封裝返回信息
responseContainer 字符串
@ApiModel 和 @ApiModelProperty 的使用

在實際的項目中我們常常會封裝一個對象作為返回值,@ApiModel 就是負責描述對象的信息,@ApiModelProperty 負責描述對象中屬性的相關內容。

@ApiModel(description = "響應對象")
public class BaseResult<T> {

    private static final int SUCCESS_CODE = 0;
    private static final String SUCCESS_MESSAGE = "成功";

    @ApiModelProperty(value = "響應碼", name = "code", required = true, example = "" + SUCCESS_CODE)
    private int code;

    @ApiModelProperty(value = "響應消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
    private String msg;

    @ApiModelProperty(value = "響應數據", name = "data")
    private T data;

    private BaseResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    private BaseResult() {
        this(SUCCESS_CODE, SUCCESS_MESSAGE);
    }

    private BaseResult(int code, String msg) {
        this(code, msg, null);
    }

    private BaseResult(T data) {
        this(SUCCESS_CODE, SUCCESS_MESSAGE, data);
    }

    public static <T> BaseResult<T> success() {
        return new BaseResult<>();
    }

    public static <T> BaseResult<T> successWithData(T data) {
        return new BaseResult<>(data);
    }

    public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) {
        return new BaseResult<>(code, msg, null);
    }

    public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
        return new BaseResult<>(param.getCode(), param.getMsg(), null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }



    public static class ResponseParam {
        private int code;
        private String msg;

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

        public static ResponseParam buildParam(int code, String msg) {
            return new ResponseParam(code, msg);
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

}

  

@PatchMapping(value="/message/text")
public BaseResult<Message> patch(Message message) {
    Message messageResult=this.messageRepository.updateText(message);
    return BaseResult.successWithData(messageResult);
}
屬性名稱 備注
value 屬性描述
name 如果配置覆蓋屬性名稱
allowableValues 允許的值
access 可以不配置
notes 沒有使用
dataType 數據類型
required 是否為必傳參數
position 顯示的順序位置
hidden 是否因此
example 舉例
readOnly 只讀
reference 引用

4.啟動項目,進入API列表,查看地址:http://127.0.0.1:8080/swagger-ui.html


免責聲明!

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



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