spring boot:用swagger3生成接口文檔,支持全局通用參數(swagger 3.0.0 / spring boot 2.3.2)


一,什么是swagger?

1,  Swagger 是一個規范和完整的文檔框架,

    用於生成、描述、調用和可視化 RESTful 風格的 Web 服務文檔

    官方網站:

https://swagger.io/

 

2,使用swagger要注意的地方:

     在生產環境中必須關閉swagger,

     它本身只用於前后端工程師之間的溝通,

     可以專門使用一台內部服務器來展示ui供訪問,

     即使在這上面要做好安全措施

 

3,  因為swagger3.0.0已發布,本文使用了最新版

     如果有還在用2.x版本的請參考時注意區分

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,演示項目的相關信息

1,項目地址

https://github.com/liuhongdi/swagger3

 

2,項目功能說明

  演示了使用swagger3.0.0生成接口站的文檔,

  包括:通用的全局參數,

           響應時各種狀態的返回

           響應的封裝后的result格式數據

           

3,項目結構:如圖:

 

 

 

三,配置文件說明

1,pom.xml

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

說明:用springfox-boot-starter來引入swagger

 

2,application.properties

springfox.documentation.swagger-ui.enabled=true

說明:在生產環境中要設置swagger-ui的enabled值為false,

用來關閉文檔的顯示

 

四,java文件說明:

1,Swagger3Config.java

@EnableOpenApi
@Configuration
public class Swagger3Config implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        //返回文檔摘要信息
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(getGlobalRequestParameters())
                .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
    }

    //生成接口信息,包括標題、聯系人等
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文檔")
                .description("如有疑問,請聯系開發工程師老劉。")
                .contact(new Contact("劉宏締", "https://www.cnblogs.com/architectforest/", "371125307@qq.com"))
                .version("1.0")
                .build();
    }

    //生成全局通用參數
    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("appid")
                .description("平台id")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("udid")
                .description("設備的唯一id")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("version")
                .description("客戶端的版本號")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
         return parameters;
    }

    //生成通用響應信息
    private List<Response> getGlobalResonseMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("404").description("找不到資源").build());
         return responseList;
    }
}

說明:生成了全局的參數和通用的響應信息

 

2,RestResult.java

@ApiModel("api通用返回數據")
public class RestResult<T> {

    //uuid,用作唯一標識符,供序列化和反序列化時檢測是否一致
    private static final long serialVersionUID = 7498483649536881777L;
    //標識代碼,0表示成功,非0表示出錯
    @ApiModelProperty("標識代碼,0表示成功,非0表示出錯")
    private Integer code;

    //提示信息,通常供報錯時使用
    @ApiModelProperty("提示信息,供報錯時使用")
    private String msg;

    //正常返回時返回的數據
    @ApiModelProperty("返回的數據")
    private T data;

    //constructor
    public RestResult() {
    }

    //constructor
    public RestResult(Integer status, String msg, T data) {
        this.code = status;
        this.msg = msg;
        this.data = data;
    }

    //返回成功數據
    public RestResult success(T data) {
        return new RestResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), data);
    }

    public static RestResult success(Integer code,String msg) {
        return new RestResult(code, msg, null);
    }

    //返回出錯數據
    public static RestResult error(ResponseCode code) {
        return new RestResult(code.getCode(), code.getMsg(), null);
    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer 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;
    }

說明:這里要注意使用泛型T,如果只用Object,則swagger不能識別我們所返回的數據的類型說明:

         其中:ApiModel用於類上面說明功能,

               ApiModelProperty用於字段上說明功能

        尤其是getData方法的返回數據類型,要用T,使用工具生成的data類容易出現這種錯誤,

       

3,Goods.java

@ApiModel("商品模型")
public class Goods {
    //商品id
    @ApiModelProperty("商品id")
    Long goodsId;
    public Long getGoodsId() {
        return this.goodsId;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }

    //商品名稱
    @ApiModelProperty("商品名稱")
    private String goodsName;
    public String getGoodsName() {
        return this.goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    //商品標題
    @ApiModelProperty("商品標題")
    private String subject;
    public String getSubject() {
        return this.subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }

    //商品價格
    @ApiModelProperty("商品價格")
    private BigDecimal price;
    public BigDecimal getPrice() {
        return this.price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    //庫存
    @ApiModelProperty("商品庫存")
    int stock;
    public int getStock() {
        return this.stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }

    public String toString(){
        return " Goods:goodsId=" + goodsId +" goodsName=" + goodsName+" subject=" + subject+" price=" + price+" stock=" + stock;
    }
}

 

4,GoodsController.java

@Api(tags = "商品信息管理接口")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Operation(summary = "商品詳情,針對得到單個商品的信息")
    @GetMapping("/one")
    public RestResult<Goods> one(@Parameter(description = "商品id,正整數") @RequestParam(value="goodsid",required = false,defaultValue = "0") Integer goodsid) {
        Goods goodsone = new Goods();
        goodsone.setGoodsId(3L);
        goodsone.setGoodsName("電子書");
        goodsone.setSubject("學python,學ai");
        goodsone.setPrice(new BigDecimal(60));
        goodsone.setStock(10);
        RestResult res = new RestResult();
        return res.success(goodsone);
    }

    @Operation(summary = "提交訂單")
    @PostMapping("/order")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userid",value="用戶id",dataTypeClass = Long.class, paramType = "query",example="12345"),
            @ApiImplicitParam(name="goodsid",value="商品id",dataTypeClass = Integer.class, paramType = "query",example="12345"),
            @ApiImplicitParam(name="mobile",value="手機號",dataTypeClass = String.class, paramType = "query",example="13866668888"),
            @ApiImplicitParam(name="comment",value="發貨備注",dataTypeClass = String.class, paramType = "query",example="請在情人節當天送到")
    })

    public RestResult<String> order(@ApiIgnore @RequestParam Map<String,String> params) {
        System.out.println(params);
        RestResult res = new RestResult();
        return res.success("success");
    }
}

說明:Api用來指定一個controller中的各個接口的通用說明

        Operation:用來說明一個方法

        @ApiImplicitParams:用來包含多個包含多個 @ApiImplicitParam,

        @ApiImplicitParam:用來說明一個請求參數 

       如果使用@Parameter來做說明,可以直接加到@RequestParam參數之前         

       @ApiIgnore:用來忽略不必要顯示的參數

 

五,效果測試

1,訪問文檔:訪問:

http://127.0.0.1:8080/swagger-ui/index.html

可以看到已有的接口:

 

 

 

2,查看接口的詳情:

參數:可以看到我們添加的全局通用參數

 

響應:

 

 

 

六,查看spring boot的版本

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

 


免責聲明!

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



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