一、swagger詳解

前言

swagger爲項目的api規範文檔,幫助咱們進行開發的。在找不一樣遊戲中有詳細用到。css

一、項目構建

1.一、pom依賴

<!--swagger 版本-->
        <swagger.version>2.7.0</swagger.version>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

所有pom文件以下
html

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hlj.swagger</groupId>
    <artifactId>com-hlj-swagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>com-hlj-swagger</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <!--swagger 版本-->
        <swagger.version>2.7.0</swagger.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

1.二、SpringBoot添加配置config支持swagger

一、添加掃描路徑com下的全部的api文件
二、api文件的說明,也就是標題。本身隨意設置嘍java


package com.hlj.swagger.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

//import springfox.documentation.service.Contact;

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))//掃描com路徑下的api文檔
                .paths(PathSelectors.any())//路徑判斷
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger 開發規範")//標題
                .description("Saggger 開發規範詳文檔細地址(HealerJean博客)--->>>>>>>:http://blog.healerjean.top/")//描述
                .termsOfServiceUrl("http://blog.healerjean.top/")//(不可見)條款地址
                .version("1.0.0")//版本號
                .build();
    }

}

1.三、啓動tomcat進行觀察

這裏個人端口設置了8082git

http://localhost:8082/swagger-ui.html#/github

WX20180326-103236@2x

二、開始添加一個demo

2.一、返回的實體對象

#### 2.1.一、@ApiModel(description = 「我是User描述」) 

對實體的描述,其實也沒什麼用,能夠直接不填。好比,找不一樣就沒有填web

2.1.二、@ApiModelProperty(value = 「用戶的姓名,好比’李四’」)

對字段的描述
一、能夠做爲返回結果的描述和
二、關於User對象參數時候的內部參數的描述spring

package com.hlj.swagger.bean;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
public class User {

    @ApiModelProperty(value = "用戶的姓名,好比'李四'")
    private String name;
    @ApiModelProperty(value = "id",required = true)
    private String id;
    @ApiModelProperty(value = "用戶的年齡,好比:20")
    private Integer age;

    @ApiModelProperty(value = "用戶的子類,測試用",required = true)
    private Base base;


    get set 省略

下面這個是嵌入類,必定要添加無參構造函數,不然不能初始化它apache

package com.hlj.swagger.bean;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "User內部對象")
public class Base {
    @ApiModelProperty(value = "baseId,好比:20")
    private int baseId;

    public int getBaseId() {
        return baseId;
    }

    public void setBaseId(int baseId) {
        this.baseId = baseId;
    }
   //必須添加
    public Base() {
    }

    public Base(int baseId) {
        this.baseId = baseId;
    }
}

2.二、controler

2.2.一、@Api 標記一個Controller類作爲swagger文檔資源,以及該Controller的描述

@Api(value = 「用戶管理」,description = 「用戶管理」)json

2.2.二、 @ApiOperation每個url資源的說明,能夠隨意定製返回的類型

@ApiOperation(value = 「獲取用戶列表」,notes = 「根據url的id來獲取用戶詳細信息,返回List類型用戶信息的JSON;」)api

2.2.三、@ApiImplicitParams 入參的描述

一、name 參數名稱

二、value,參數說明

三、required 參數是否必填,當出現參數爲對象時候,對象中的必填項能夠在實體中
ApiModelProperty進行編輯

四、paramType http請求的類型 query爲請求參數,表示在controller方法中定義的參數(基本類型),但若是是是參數是,對象則不須要配置。無關Get和Post方法

五、dataType 參數類型

@ApiImplicitParams({
     @ApiImplicitParam(name = "id",
                                value = "用戶Id", 
                                required = true, 
                                paramType = "query"
                                dataType = "string")
package com.hlj.swagger.controller;

import com.hlj.swagger.bean.Base;
import com.hlj.swagger.bean.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(value = "用戶管理",description = "用戶管理")
@RestController
@RequestMapping("/user")
public class UserController {

Logger log = LoggerFactory.getLogger(UserController.class);

@ApiOperation(value = "獲取用戶列表", notes = "根據url的id來獲取用戶詳細信息,返回List<User>類型用戶信息的JSON;")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用戶ID", required = true, paramType = "query",dataType = "string")

})
@GetMapping("one")
public List<User> getUserBagOne(String id) {
    List<User> users = new ArrayList<>();
    try {
        if (id.equals("1")) {
            users.add(new User("HealerJean", "1", 24, new Base(1)));
        } else {
            users.add(new User("huangliang", "2", 25, new Base(2)));
        }
        return users;
    } catch (Exception e) {
        return users;
    }

}
}

2.三、瀏覽器啓動,開始測試

http://localhost:8081/swagger-ui.html#/

WX20180326-135830@2x

解釋上面爲返回值,下面爲輸入參數

WX20180326-141124@2x

能夠看到下面中會出現這個url的描述,以及請求參數和返回的結果舉例,點擊Model會看到結果參數的說明

WX20180326-122416@2x


WX20180326-135736@2x

2.3.1 輸入參數id爲1 和2分別查看結果 try it out

WX20180326-140019@2x

三、修改2中獲取結果的對象,設置爲包裝對象Response

3.一、包裝對象

這裏其實能夠清晰的看到下面data其實就是咱們正兒八經返回的結果

package com.hlj.swagger.common;


/** * @author fengchuanbo */
public class Response<T> {

    /** * 返回code */
    private String code;
    /** * 返回描述 */
    private String desc;
    /** * 返回數據 */
    private T data;

    public Response(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public Response(Code code) {
        this.code = code.getCode();
        this.desc = code.getDesc();
    }

    public Response(Code code, T data) {
        this.code = code.getCode();
        this.desc = code.getDesc();
        this.data = data;
    }

    /** * 成功響應 * @param t * @param <T> * @return */
    public static <T> Response<T> success(T t){
        return new Response<>(Code.OK, t);
    }

    /** * 成功響應,date爲空 * @return */
    public static Response success(){
        return new Response(Code.OK);
    }

    /** * 參數錯誤 * @return */
    public static Response illegalArgument(){
        return new Response(Code.illegalArgument);
    }


    /** * 自定義返回 * @param code * @param desc * @return */
    public static <T> Response of(String code,String desc, T t){
        return new Response(code,desc,t);
    }


    /** * 自定義返回 * @param code * @param desc * @return */
    public static Response of(String code,String desc){
        return new Response(code,desc);
    }


    /** * 自定義返回 * @param code * @param t * @return */
    public static <T> Response of(Code code, T t){
        return new Response(code,t);
    }

    /** * 自定義返回 * @param code * @return */
    public static Response of(Code code){
        return new Response(code);
    }


    /** * 系統錯誤 * @return */
    public static Response error() {
        return new Response(Code.ERROR);
    }

    get set 省略

}

3.二、修改controller中的方法

一、修改 ApiOperation(實施說明) 中添加返回數據格式就能夠,以下

@ApiOperation(value = "獲取用戶列表",
                        notes = "根據url的id來獲取用戶詳細信息,返回List<User>類型用戶信息的JSON;",
                        response = User.class,responseContainer = "List",
                        //application/json 返回結果的類型
                        produces = MediaType.APPLICATION_JSON_VALUE,
                        //multipart/form-data 返回的數據格式
                        consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation(value = "獲取用戶列表",notes = "根據url的id來獲取用戶詳細信息,返回List<User>類型用戶信息的JSON;",response = User.class,responseContainer = "List",produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用戶ID", required = true, paramType = "query",dataType = "string") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 請求已完成"), @ApiResponse(code = 400, message = "請求中有語法問題,或不能知足請求"), @ApiResponse(code = 401, message = "未受權客戶機訪問數據"), @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"), @ApiResponse(code = 500, message = "服務器不能完成請求")} ) @GetMapping("two") public Response<?> getUserBagTwo(String id){ List<User> users = new ArrayList<>(); try { if(id.equals("1")) { users.add(new User("HealerJean", "1", 24, new Base(1))); }else { users.add(new User("huangliang", "2", 25, new Base(2))); } return Response.success(users); }catch (Exception e){ return Response.error(); } } 

二、運行項目(這個時候我將第一個demo路徑修改爲了one,本次爲two)

WX20180326-123635@2x

這個時候,就看到實際上是List(User)中的內容了。而不是Response對象中的內容

WX20180326-123709@2x

四、添加系統提供的http返回狀態碼描述

一、ApiResponses

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful — 請求已完成"), @ApiResponse(code = 400, message = "請求中有語法問題,或不能知足請求"), @ApiResponse(code = 401, message = "未受權客戶機訪問數據"), @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"), @ApiResponse(code = 500, message = "服務器不能完成請求")} ) 
@ApiOperation(value = "獲取用戶列表",notes = "根據url的id來獲取用戶詳細信息,返回List<User>類型用戶信息的JSON;",response = User.class,responseContainer = "List",produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "string")

})
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful — 請求已完成"),
        @ApiResponse(code = 400, message = "請求中有語法問題,或不能知足請求"),
        @ApiResponse(code = 401, message = "未受權客戶機訪問數據"),
        @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"),
        @ApiResponse(code = 500, message = "服務器不能完成請求")}
)
@GetMapping("two")
public Response<?> getUserBagTwo(String id){
    List<User> users = new ArrayList<>();
    try {
        if(id.equals("1")) {
            users.add(new User("HealerJean", "1", 24, new Base(1)));
        }else {
            users.add(new User("huangliang", "2", 25, new Base(2)));
        }
        return Response.success(users);
    }catch (Exception e){
        return Response.error();
    }

}

以前
WX20180326-132132@2x

以後

WX20180326-132053@2x

五、根據id-/{id}獲取User

一、dataType = 「path」 表示在請求頭上直接寫入參數

一、controller

@ApiOperation(value = "根據id獲取用戶詳細信息", notes = "根據url的id來獲取用戶詳細信息")
//描述容器
@ApiImplicitParam(name = "id", value = "用戶ID", required = true,  paramType = "query",dataType = "path")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(String id) {
    return new User("HealerJean", id, 24, new Base(1));
}

WX20180326-141020@2x

六、Post方法傳入User對象參數

一、user 不須要配置 paramType ,默認都是body

@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User"),
@ApiOperation(value = "建立用戶", notes = "根據User對象建立用戶")
@ApiImplicitParams({
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User"),
        @ApiImplicitParam(name = "flag", value = "是否開啓標誌位", paramType = "query", dataType = "boolean"),
        @ApiImplicitParam(name = "version", value = "版本號", required = true, paramType = "query", dataType = "string")

})
@RequestMapping(value = "", method = RequestMethod.POST)
public User postUser(User user, @RequestParam(defaultValue = "false") boolean flag, String version) {
    log.info(flag+"");
    log.info(version);
    return user;
}

6.二、開始測試

一、user 對象也不須要輸入值,只輸入{}便可
二、測試成功

錯誤分析:若是當調用獲得base.baseId輸入後臺報錯的時候,說明base中沒有空構造函數致使不能初始化。

WX20180326-144606@2x

WX20180326-144637@2x

代碼下載





若是滿意,請打賞博主任意金額,感興趣的請下方留言吧。可與博主自由討論哦

支付包 微信 微信公衆號
支付寶 微信 微信公衆號
相關文章
相關標籤/搜索