springboot 集成swagger接口視圖展示

springboot 項目的新建我在這裏就不贅述了,不會的朋友可以自行學習一下。

多的不講,直接上代碼

1.項目的結構

2.pom.xml文件中加入依賴

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.49</version>
</dependency>

3.config配置文件類中加入swagger配置類

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
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.List;

/**
 * @author zxw
 * @description
 * @date 2018/8
 */

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter>  parameters       = new ArrayList<>();
        parameterBuilder.name("Authorization").description("token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();
        parameters.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameters)
                .apiInfo(apiInfo());


    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("demo")
                .description("測試")
                .contact("zxw")
                .version("1.0")
                .build();
    }

}

4.swagger相關使用註解

常用到的註解有:

  • Api
  • ApiModel
  • ApiModelProperty
  • ApiOperation
  • ApiParam
  • ApiResponse
  • ApiResponses
  • ResponseHeader

1. api標記

Api 用在類上,說明該類的作用。可以標記一個Controller類做爲swagger 文檔資源,使用方式:

@Api(value = "/user", description = "Operations about user")

與Controller註解並列使用。 屬性配置:

屬性名稱 備註
value url的路徑值
tags 如果設置這個值、value的值會被覆蓋
description 對api資源的描述
basePath 基本路徑可以不配置
position 如果配置多個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 將在文檔中隱藏

在SpringMvc中的配置如下:

@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {

}

2. ApiOperation標記

ApiOperation:用在方法上,說明方法的作用,每一個url資源的定義,使用方式:

@ApiOperation(
          value = "Find purchase order by ID",
          notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
          response = Order,
          tags = {"Pet Store"})

與Controller中的方法並列使用。
屬性配置:

屬性名稱 備註
value url的路徑值
tags 如果設置這個值、value的值會被覆蓋
description 對api資源的描述
basePath 基本路徑可以不配置
position 如果配置多個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 擴展屬性

在SpringMvc中的配置如下:

@RequestMapping(value = "/order/{orderId}", method = GET)
  @ApiOperation(
      value = "Find purchase order by ID",
      notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
      response = Order.class,
      tags = { "Pet Store" })
   public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
      throws NotFoundException {
    Order order = storeData.get(Long.valueOf(orderId));
    if (null != order) {
      return ok(order);
    } else {
      throw new NotFoundException(404, "Order not found");
    }
  }

3. ApiParam標記

ApiParam請求屬性,使用方式:

public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true)  User user)

與Controller中的方法並列使用。

屬性配置:

屬性名稱 備註
name 屬性名稱
value 屬性值
defaultValue 默認屬性值
allowableValues 可以不配置
required 是否屬性必填
access 不過多描述
allowMultiple 默認爲false
hidden 隱藏該屬性
example 舉例子

在Springboot中的配置如下:

 public ResponseEntity<Order> getOrderById(
      @ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
      @PathVariable("orderId") String orderId)

4. ApiResponse

ApiResponse:響應配置,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied")

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
code http的狀態碼
message 描述
response 默認響應類 Void
reference 參考ApiOperation中配置
responseHeaders 參考 ResponseHeader 屬性配置說明
responseContainer 參考ApiOperation中配置

在SpringMvc中的配置如下:

 @RequestMapping(value = "/order", method = POST)
  @ApiOperation(value = "Place an order for a pet", response = Order.class)
  @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
  public ResponseEntity<String> placeOrder(
      @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
    storeData.add(order);
    return ok("");
  }

5. ApiResponses

ApiResponses:響應集配置,使用方式:

 @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
value 多個ApiResponse配置

在SpringMvc中的配置如下:

 @RequestMapping(value = "/order", method = POST)
  @ApiOperation(value = "Place an order for a pet", response = Order.class)
  @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
  public ResponseEntity<String> placeOrder(
      @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
    storeData.add(order);
    return ok("");
  }

6. ResponseHeader

響應頭設置,使用方法

@ResponseHeader(name="head1",description="response head conf")

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
name 響應頭名稱
description 頭描述
response 默認響應類 Void
responseContainer 參考ApiOperation中配置

在SpringMvc中的配置如下:

@ApiModel(description = "羣組")

7. 其他

  • @ApiImplicitParams:用在方法上包含一組參數說明;
  • @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
    • paramType:參數放在哪個地方
    • name:參數代表的含義
    • value:參數名稱
    • dataType: 參數類型,有String/int,無用
    • required : 是否必要
    • defaultValue:參數的默認值
  • @ApiResponses:用於表示一組響應;
  • @ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應信息;
    • code: 響應碼(int型),可自定義
    • message:狀態碼對應的響應信息
  • @ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam註解進行描述的時候;
  • @ApiModelProperty:描述一個model的屬性。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章