SpringMVC集成Swagger

1. 簡介

  Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新 。接口的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。html

2. 添加Swagger2依賴

注意:
只添加下面兩個依賴的前提是SpringMVC的項目可以正常運行web

<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>2.6.1</version>
</dependency>

<!--swagger-ui是提供API接口頁面展現的-->
<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>2.6.1</version>
</dependency>

3. 建立Swagger2配置類

3.1 自定義配置類

//啓用Swagger2
@EnableSwagger2        
public class Swagger2Config extends WebMvcConfigurationSupport {
   
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).select()
                //掃描指定包中的swagger註解
                //.apis(RequestHandlerSelectors.basePackage("com.xia.controller"))
                //掃描全部有註解的api,用這種方式更靈活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }


    @Bean
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("基礎平臺 RESTful APIs")
                .description("基礎平臺 RESTful 風格的接口文檔,內容詳細,極大的減小了先後端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減小維護文檔的時間。")
                .termsOfServiceUrl("http://xiachengwei5.coding.me")
                .version("1.0.0")
                .termsOfServiceUrl("http://xxx.xxx.com")
                .license("LICENSE")
                .licenseUrl("http://xxx.xxx.com")
                .build();
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
}

3.2 使用xml中配置

<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/>
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

4. 初步展現效果

image

5. 編寫經常使用Swagger註解

添加Swagger註解,可以讓Swagger的APi文檔頁面更加友好,更加方便理解和調試spring

5.1 實體註解

  • @ApiModel() 用於類,表示對類進行說明,用於參數用實體類接收後端

    • value–表示對象名
    • description–描述
  • @ApiModelProperty() 用於方法,字段;表示對model屬性的說明或者數據操做更改api

    • value:字段說明
    • name:重寫屬性名字
    • dataType:重寫屬性類型
    • required:是否必填
    • example:舉例說明
    • hidden:隱藏

用法以下代碼所示:數組

@ApiModel(value = "UserInfo:用戶信息")
public class UserInfo implements Serializable {
    @ApiModelProperty(value = "ID")
    private Integer id;

    @ApiModelProperty(value = "登陸帳號", required = true)
    private String userNo;

    @ApiModelProperty(value = "姓名", required = true)
    private String userName;
}

顯示效果以下所示:服務器

image

5.2 控制類註解

下面的這些註解都放在Controller控制器類上面mvc

5.2.1 @Api

修飾整個類,描述Controller的做用app

@Api(tags = {"用戶操做接口"})
@RestController
@RequestMapping(value = "/userInfo")
public class UserInfoController {

}
  • tags:控制類功能說明,tags是一個字符串數組,能夠添加多個標籤
tags = {"用戶操做接口","對用戶的一些增刪改查操做"}

效果以下:框架

image

  • value:也是說明,可使用tags替代

5.2.2 @ApiOperation

描述一個類的一個方法,或者說一個接口

@GetMapping(value = "/selectOne")
    @ApiOperation(value = "value做用:查詢單我的員信息", notes = "notes做用:輸入用戶ID",tags = {"查詢"})
    public ZingResult selectOne() {
        return ZingResult.success();
    }

    @GetMapping(value = "/update")
    @ApiOperation(value = "value做用:更新用戶信息", notes = "notes做用:輸入用戶各項參數",tags = {"更新"})
    public ZingResult update() {
        return ZingResult.success();
    }
  • value用於方法描述
  • notes用於提示內容

image

  • tags能夠從新分組

image

5.2.3 @ApiParam

單個參數描述

  • name–參數名
  • value–參數說明
  • required–是否必填
@GetMapping(value = "/selectOne")
    @ApiOperation(value = "value做用:查詢全部的人員信息並分頁展現", notes = "notes做用:輸入page和size來分頁查詢", tags = {"查詢"})
    public ZingResult selectOne(@ApiParam(name="page",value="頁碼",required=true) Integer page,@ApiParam(name="size",value="數量",required=true) Integer size) {
        return ZingResult.success();
    }

image

5.2.4 @ApiImplicitParams()和@ApiImplicitParam

用於方法,包含多個@AplimplicitParam

  • name–參數ming
  • value–參數說明
  • dataType–數據類型
  • paramType–參數類型
  • example–舉例說明
@ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "跳轉到的頁數", required = true, paramType = "query"),
        @ApiImplicitParam(name = "size", value = "每頁展現的記錄數", required = true, paramType = "query")
})
public ZingResult selectAllUsers(Integer page, Integer size) {
    return ZingResult.success();
}

效果以下圖所示:

image

5.2.5 @ApiIgnore()

用於類或者方法上,能夠不被swagger顯示在頁面上
比較簡單, 這裏不作舉例

6. 加載配置文件

加載配置文件中的內容,靈活配置swagger APIinfo的信息

注意Spring的@Value讀取配置文件中的中文會亂碼

6.1 配置文件

#Swagger開關
SWAGGER.ENABLE = true

#Swagger API配置
SWAGGER.TITLE = 基礎平臺 RESTful APIs
SWAGGER.DESC = 基礎平臺 RESTful 風格的接口文檔,內容詳細,極大的減小了先後端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減小維護文檔的時間。

6.2 加載配置文件,並制定utf-8編碼

  • 使用PropertyPlaceholderConfigurer加載
<!-- 加載配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:dubbo-server.properties</value>
            <value>classpath:server.properties</value>
        </list>
    </property>
    <property name="fileEncoding" value="utf-8" />
</bean>
  • 使用context:property-placeholder 加載
<context:property-placeholder location="classpath:conf/*.properties" file-encoding="UTF-8"/>
  • 使用註解加載
@PropertySource(value = "classpath:conf/copyWriteUI.properties",encoding = "utf-8")
相關文章
相關標籤/搜索