spring-mvc使用swagger生成API說明文檔

使用swagger生成API說明文檔

本文由個人總結,如需轉載使用請標明原著及原文地址

明明沒有導出還是好多人留言  →_→  好煩啊  所以我浪費了半天時間挖了個swagger導出的坑    ↓↓↓  自己去看吧

 https://blog.csdn.net/qq_36911145/article/details/103970876

SwaggerDemo,jar包使用maven進行管理,還沒了解maven的小夥伴可能有無法使用的情況

在做前後端分離的項目時,後端人員總是要寫接口文檔給其他使用者,大家都知道,寫接口文檔是一件吃力不討好的事,而swagger就是爲了解決這個問題而存在的,不僅能提供接口文檔,還能提供簡單的傳參測試

要使用swagger,首先你要有一個spring項目

1.導包

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
    </dependency>

我這使用maven統一管理jar包,在pom.xml中加入上面兩個dependency,maven就能自動下載對應jar包,不瞭解maven的小夥伴自行在百度上找jar包,然後手動導入項目

springfox-swagger2-vesion.jar

springfox-swagger-ui-vesion.jar

2.寫一個swagger配置類

package cn.ycyy.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author Devil
 * @create 2018-09-26 19:16
 */
@EnableSwagger2
@ComponentScan(basePackages = {"cn.ycyy.controller"})
@Configuration
public class SwaggerConfig extends WebMvcConfigurationSupport{
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("《SwaggerDemo的演示案例--》")//標題
                .description("description:項目摘要")//描述
                .termsOfServiceUrl("http://www.google.com.hk")//(不可見)條款地址,公司內部使用的話不需要配
                .contact(new Contact("Devil", "https://blog.csdn.net/qq_36911145", "[email protected]"))//作者信息
                .version("6.6.6")//版本號
                .build();
    }
}

創建的SwaggerConfig要繼承WebMvcConfigurationSupport

@EnableSwagger2 swagger2啓動註解
@ComponentScan(basePackages = {"cn.ycyy.controller"}) 指定需要生成API文檔的類所在的包路徑
@Configuration 聲明這是一個配置類

createRestApi方法不需要更改,主要用於swagger的初始化設置,包括掃描API註解路徑等,用我提供的createRestApi默認掃描當前項目全部路徑,這裏的掃描與上面的@ComponentScan不同,這裏掃描的不會顯示在swagger-ui(swaggerAPI文檔可視化界面,最後會說)上

apiInfo裏的參數設置對應效果如下圖所示

 

SwaggerConfig文件必須放在spring註解掃描器能掃描到的位置,例如說我的項目都放在cn.ycyy項目下,我指定掃描路徑cn.ycyy那麼spring就能把整個項目的註解都掃描到

    <context:component-scan base-package="cn.ycyy">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

然後將項目啓動發佈到tomcat上,就能訪問swaggerAPI了

訪問的URL也是個固定的格式

http://ip地址:端口/項目名/swagger-ui.html#/

3.配置api生成

在先前說了,這裏只會顯示@ComponentScan(basePackages = {"cn.ycyy.controller"}),這個路徑下的類生成的API

我的測試案例中只寫了一個UserController所以這裏只顯示,UserController及裏面的方法

UserController代碼如下

package cn.ycyy.controller;

import cn.ycyy.bean.User;
import cn.ycyy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * @author Devil
 * @create 2018-09-28 15:36
 */
@Controller
@Api(value="aaaaaaa",description="User的相關信息接口")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/getAll")
    @ResponseBody
    @ApiOperation(value="獲取所有user",notes="獲取所有user,無需參數", httpMethod = "POST")
    public String getAll(){
        //查出的所有部門信息
        List<User> list = userService.selectAll();
        return list.toString();
    }
    @RequestMapping("/getOne")
    @ResponseBody
    @ApiOperation(value="獲取單個user",notes="獲取單個user,需參數", httpMethod = "POST")
    public String getOne(@Valid User user, BindingResult result){
        //查出的所有部門信息
        List<User> list = userService.selectBy(user);
        return list.toString();
    }
    @RequestMapping("/getOneByName")
    @ResponseBody
    @ApiOperation(value="獲取單個user",notes="獲取單個user,需參數", httpMethod = "POST")
    public String getOneByName(@ApiParam(value = "用戶名", required = true)String name){

        return "something";
    }
}

在類上加上@Api註解

以下參數可不指定

value 在swagger-ui上不顯示
description

在swagger-ui上有顯示,可以當做備註使用,描述這個類的信息

在新版本的swagger2中description已被淘汰,可以用tags代替,但是不更改也不會影響使用

在方法上加上@ApiOperation註解

以下參數可不指定

value 未展開狀態方法備註信息
notes 展開狀態下方法備註信息,和value相比,value是未展開狀態下的備註,一般會寫的比較簡短,而notes可以寫的比較詳細
httpMethod

指定http模式,參數有"POST"、"DELETE"、"GET"、"HEAD"等

如果方法需要前端傳遞參數,可使用@ApiParam註解

value 參數備註信息
required 是否爲必填項true爲必填

如果方法用對象入參的話,在實體類中對屬性加@ApiModelProperty註解

value 類屬性備註信息

例如我有個方法的參數用User,那麼我User類如下配置

package cn.ycyy.bean;

import io.swagger.annotations.ApiModelProperty;

/**
 * @author Devil
 * @create 2018-09-28 15:24
 */
public class User {
    @ApiModelProperty(value="用戶名")
    private String name;
    @ApiModelProperty(value="密碼")
    private String password;
    @ApiModelProperty(value="性別")
    private String gender;
    @ApiModelProperty(value="年齡")
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

效果如下所示

API文檔中會將User自動分解成User的屬性

4.註解全參數

以下是swagger2註解中的全參數,有興趣可以都試試

@Api 
Api 標記可以標記一個Controller類做爲swagger 文檔資源,使用方式

屬性名稱

備註

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 將在文檔中隱藏

@ApiOperation每一個url資源的定義,使用方式

屬性名稱

備註

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

擴展屬性

@ApiParam標記
public ResponseEntity createUser(@RequestBody @ApiParam(value = “user”, required = true) User user)

屬性名稱

備註

name

屬性名稱

value

屬性值

defaultValue

默認屬性值

allowableValues

可以不配置

required

是否屬性必填

access

不過多描述

allowMultiple

默認爲false

hidden

隱藏該屬性

example

舉例子

@ApiImplicitParam對容器的描述

屬性名稱

備註

name

屬性名稱

value

屬性值

defaultValue

默認值

allowableValues

可以不可配置

required

是否屬性必填

access

不可過多描述

allowMutiple

默認爲false

dataType

數據類型

paramType

參數類型

@ApiResponse

屬性名稱

備註

code

http的狀態碼

message

描述

response

默認響應類 Void

reference

參考ApiOperation中配置

responseHeaders

參考 ResponseHeader 屬性配置說明

responseContainer

參考ApiOperation中配置

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章