Swagger簡明教程

一、什麼是swagger

Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化RESTful風格的 Web 服務。總體目標是使客戶端和文件系統作為伺服器以同樣的速度來更新。文件的方法,參數和模型緊密集成到伺服器端的程式碼,允許API來始終保持同步。Swagger讓部署管理和使用功能強大的API變得非常簡單。

簡單來說,就是後端給前端提供的一個可以查看各種介面的方法、類型等。

二、配置swagger

1、pom.xml

 1 <!-- swagger2模組 -->
 2 <dependency>
 3     <groupId>io.springfox</groupId>
 4     <artifactId>springfox-swagger-ui</artifactId>
 5     <version>2.9.2</version>
 6 </dependency>
 7 <dependency>
 8     <groupId>io.springfox</groupId>
 9     <artifactId>springfox-swagger2</artifactId>
10     <version>2.9.2</version>
11 </dependency>

2、Swagger2Config類

在src/main/java/com/example/demo/config目錄下新建Swagger2Config類

1 /**
2  * Swagger2Configuration配置類
3  */
4 @Configuration
5 @EnableSwagger2
6 public class Swagger2Config {
7 }

3、Docket方法

源碼

 1 this.apiInfo = ApiInfo.DEFAULT;         //用於定義api文檔匯總資訊
 2 this.groupName = "default";
 3 this.enabled = true;
 4 this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
 5 this.applyDefaultResponseMessages = true;
 6 this.host = "";
 7 this.pathMapping = Optional.absent();
 8 this.apiSelector = ApiSelector.DEFAULT;
 9 this.enableUrlTemplating = false;
10 this.vendorExtensions = Lists.newArrayList();
11 this.documentationType = documentationType;

調用

 1 @Bean
 2 public Docket createApi(){
 3     return new Docket(DocumentationType.SWAGGER_2)
 4         .apiInfo(apiInfo())
 5         //配置分組
 6         .groupName("user")
 7         //配置是否啟動
 8         .enable(ture)
 9         .select()
10         /**
11         RequestHandlerSelectors:配置要掃描介面的方式
12         basePackage:指定要掃描的包
13         any():掃描全部
14         none():不掃描
15         withClassAnnotation:掃描類上的註解
16         withMethodAnnotation:掃描方法上的註解
17         **/
18         .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
19         //path():過濾的路徑
20         //.path(PathSelectors.ant("/xxx/*"))
21         .build();
22 }

4、ApiInfo方法

源碼

 1 public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
 2 public static final ApiInfo DEFAULT;
 3 private final String version;           //文檔版本號
 4 private final String title;             //文檔頁標題
 5 private final String description;       //詳細資訊
 6 private final String termsOfServiceUrl; //網站地址
 7 private final String license;
 8 private final String licenseUrl;
 9 private final Contact contact;          //聯繫人資訊
10 private final List<VendorExtension> vendorExtensions;

調用

1 private ApiInfo apiInfo(){
2     return new ApiInfoBuilder()
3         .title("Swagger2")
4         .description("RestFul API介面")
5         .version("1.0")
6         .build();
7 }

5、頁面效果

//localhost:8080/swagger-ui.html

 groupName可以進行分組以區分後端開發者,如果有多個後端開發者,可以在Swagger2Config類里寫多個Docket對象然後通過@Bean注入,不同的Docket對象代表不同的分組

 1 @Bean
 2 public Docket createApi1(){
 3     return new Docket(DocumentationType.SWAGGER_2)
 4         .apiInfo(apiInfo())
 5         //配置分組
 6         .groupName("user1")        //user1分組
 7         //配置是否啟動
 8         .enable(ture)
 9         .select()
10         .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
11         .build();
12 }
13 
14 @Bean
15 public Docket createApi2(){
16     return new Docket(DocumentationType.SWAGGER_2)
17         .apiInfo(apiInfo())
18         //配置分組
19         .groupName("user2")        //user2分組
20         //配置是否啟動
21         .enable(ture)
22         .select()
23         .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
24         .build();
25 }

三、Swagger常用註解

1、@ApiModel

使用場景:在實體類上使用,標記類時swagger的解析類

概述:提供有關swagger模型的其它資訊,類將在操作中用作類型時自動內省

 1 String value() default "";
 2 
 3 String description() default "";
 4 
 5 Class<?> parent() default Void.class;
 6 
 7 String discriminator() default "";
 8 
 9 Class<?>[] subTypes() default {};
10 
11 String reference() default "";
屬性名稱 數據類型 默認值 說明
value String 類名 為模型提供備用名稱
description String “” 提供詳細的類描述
parent Class<?> parent() Void.class 為模型提供父類以運行描述繼承關係
discriminator String “” 支援模型繼承和多態,使用鑒別器的欄位名稱,可以斷言需要使用哪個子類型
subTypes Class<?>[] {} 從模型繼承的子類型數組
reference String “” 指定對應類型定義的引用,覆蓋指定的任何其他元數據

示例

1 /**
2  * Student類 學生實體類
3  */
4 @ApiModel(value = "Student",description = "用戶實體類")
5 public class Student implements Serializable {
6 }

2、@ApiModelProperty

使用場景:使用在被 @ApiModel 註解的模型類的屬性上。表示對model屬性的說明或者數據操作更改

概述:添加和操作模型屬性的數據

 1 String value() default "";
 2 
 3 String name() default "";
 4 
 5 String allowableValues() default "";
 6 
 7 String access() default "";
 8 
 9 String notes() default "";
10 
11 String dataType() default "";
12 
13 boolean required() default false;
14 
15 int position() default 0;
16 
17 boolean hidden() default false;
18 
19 String example() default "";
20 
21 /** @deprecated */
22 @Deprecated
23 boolean readOnly() default false;
24 
25 ApiModelProperty.AccessMode accessMode() default ApiModelProperty.AccessMode.AUTO;
26 
27 String reference() default "";
28 
29 boolean allowEmptyValue() default false;
30 
31 Extension[] extensions() default {@Extension(
32     properties = {@ExtensionProperty(
33         name = "",
34         value = ""
35     )}
36 )};
屬性名稱 數據類型 默認值 說明
value String “” 屬性簡要說明
name String “” 重寫屬性名稱
allowableValues String “” 限制參數可接收的值,三種方法,固定取值,固定範圍
access String “” 過濾屬性
notes String “” 目前尚未使用
dataType String “” 參數的數據類型,可以是類名或原始數據類型,此值將覆蓋從類屬性讀取的數據類型
required boolean false 是否為必傳參數(false:非必傳參數;true:必傳參數)
position int “” 運行在模型中顯示排序屬性
hidden boolean false 隱藏模型屬性(false:不隱藏;true:隱藏)
example String “” 屬性的示例值
readOnly boolean false 指定模型屬性為只讀(false:非只讀;true:只讀)
reference String “” 指定對應類型定義的引用,覆蓋指定的任何其他元數據
allowEmptyValue boolean false 運行穿空值(false:不允許傳空值;true:運行傳空值)
extensions Extension[] {@Extension(properties={@ExtensionProperty(name = “”,value = “”)})}; 關聯註解

示例

 1 @ApiModelProperty(value = "學號")
 2 private Integer id;         //學號
 3 @ApiModelProperty(value = "姓名")
 4 private String name;        //姓名
 5 @ApiModelProperty(value = "成績")
 6 private Integer score;      //成績
 7 @ApiModelProperty(value = "籍貫")
 8 private String birthplace;  //籍貫
 9 //日期的格式 年-月-日
10 @ApiModelProperty(value = "生日")
11 @DateTimeFormat(pattern = "yyyy-MM-dd")
12 private Date birthday;      //生日

3、@ApiOperation

使用場景:使用在方法上,表示一個http請求的操作

概述:用來表示Controller類下的http請求方法

 1 String value();
 2 
 3 String notes() default "";
 4 
 5 String[] tags() default {""};
 6 
 7 Class<?> response() default Void.class;
 8 
 9 String responseContainer() default "";
10 
11 String responseReference() default "";
12 
13 String httpMethod() default "";
14 
15 /** @deprecated */
16 @Deprecated
17 int position() default 0;
18 
19 String nickname() default "";
20 
21 String produces() default "";
22 
23 String consumes() default "";
24 
25 String protocols() default "";
26 
27 Authorization[] authorizations() default {@Authorization("")};
28 
29 boolean hidden() default false;
30 
31 ResponseHeader[] responseHeaders() default {@ResponseHeader(
32     name = "",
33     response = Void.class
34 )};
35 
36 int code() default 200;
37 
38 Extension[] extensions() default {@Extension(
39     properties = {@ExtensionProperty(
40         name = "",
41         value = ""
42     )}
43 )};
44 
45 boolean ignoreJsonView() default false;
屬性名稱 數據類型 默認值 說明
value String   屬性簡要說明
notes String “” 備註說明
tags String {“”} 可重新分組
response Class<?> response() Void.class 用於描述消息有效負載的可選響應類,對應於響應消息對象的 schema 欄位
responseContainer String “” 聲明響應的容器,有效值為List,Set,Map,任何其他值都將被忽略
responseReference String “” 聲明響應的引用
httpMethod String “” http請求方式
position int 0 運行在模型中顯示排序屬性
nickname String “” 昵稱
produces String “” For example, “application/json, application/xml”
consumes String “” For example, “application/json, application/xml”
protocols String “” Possible values: http, https, ws, wss.
authorizations Authorization[] {@Authorization(“”)} 高級特性認證時配置
hidden boolean false 是否隱藏
responseHeaders ResponseHeader[] {@ResponseHeader(name = “”,response = Void.class)}; 可能響應的 header 列表
code int 200 http狀態碼
extensions Extension[] {@Extension(properties = {@ExtensionProperty(name = “”,value = “”)})}; 關聯註解
ignoreJsonView boolean false 是否忽略json視圖

示例

1 @ApiOperation("添加學生資訊")
2 @PostMapping(value = "/student")
3 public void AddStudent(Student student) {
4 
5     studentService.AddStudent(student);
6 }

4、@ApiParam

使用場景:在 Rest 介面上或 Rest 介面參數前邊使用

概述:為 Rest 介面參數添加其它元數據(導入到 yapi 中不會被解析)

 1 String name() default "";
 2 
 3 String value() default "";
 4 
 5 String defaultValue() default "";
 6 
 7 String allowableValues() default "";
 8 
 9 boolean required() default false;
10 
11 String access() default "";
12 
13 boolean allowMultiple() default false;
14 
15 boolean hidden() default false;
16 
17 String example() default "";
18 
19 Example examples() default @Example({@ExampleProperty(
20     mediaType = "",
21     value = ""
22 )});
23 
24 String type() default "";
25 
26 String format() default "";
27 
28 boolean allowEmptyValue() default false;
29 
30 boolean readOnly() default false;
31 
32 String collectionFormat() default "";
屬性名稱 數據類型 默認值 說明
name String “” 參數名稱,參數名稱將從 filed/method/parameter 名稱中派生,但你可以覆蓋它,路徑參數必須始終命名為它們所代表的路徑部分
value String “” 參數簡單描述
defaultValue String “” 描述參數默認值
allowableValues String “” 可接收參數值限制,有三種方式,取值列表,取值範圍
required boolean false 是否為必傳參數(false:非必傳; true:必傳)
access String “” 參數過濾
allowMultiple boolean false 指定參數是否可以通過多次出現來接收多個值
hidden boolean false 隱藏參數列表中的參數
example String “” 非請求體(body)類型的單個參數示例
examples Example @Example({@ExampleProperty(mediaType = “”,value = “”)}); 參數示例,僅適用於請求體類型的請求
type String “” 添加覆蓋檢測到類型的功能
format String “” 添加提供自定義format格式的功能
allowEmptyValue boolean false 添加將格式設置為空的功能
readOnly boolean false 添加被指定為只讀的能力
collectionFormat String “” 添加使用 array 類型覆蓋 collectionFormat 的功能

示例

1 @ApiOperation("判斷驗證碼是否正確")
2 @RequestMapping(value = "/UpdatePassword" , method = RequestMethod.POST)
3 public CommonResult updatePassword(
4     @ApiParam(value = "手機號碼",required = true) @RequestParam String userPhone,
5     @ApiParam(value = "驗證碼",required = true) @RequestParam String authCode){
6 
7     return userMemberService.updatePassword(userPhone,authCode);
8 }

5、頁面效果

1.@ApiModel與@ApiModelProperty效果

2.@ApiOperation效果

四、導出swagger介面文檔

1、導入模組依賴

pom.xml文件

1 <!-- swagger2markup模組 -->
2 <dependency>
3     <groupId>io.github.swagger2markup</groupId>
4     <artifactId>swagger2markup</artifactId>
5     <version>1.3.1</version>
6 </dependency>

2、新增測試類

在src/test/java/com/example/demo目錄下新建測試類SwaggerTo

SwaggerTo

1 @RunWith(SpringRunner.class) //測試類要使用注入的類
2 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) //用於單元測試
3 public class SwaggerTo {
4 }

3、新增測試方法

generateMarkdownDocs()

 1 /**
 2   * 生成Markdown格式文檔
 3   * @throws Exception
 4   */
 5 @Test
 6 public void generateMarkdownDocs() throws Exception {
 7     //    輸出Markdown格式
 8     Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
 9         .withMarkupLanguage(MarkupLanguage.MARKDOWN)    //輸出格式:ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10         .withOutputLanguage(Language.ZH)                //語言類型:中文(ZH) 默認英文(EN)
11         .withPathsGroupedBy(GroupBy.TAGS)               //Api排序規則
12         .withGeneratedExamples()
13         .withoutInlineSchema()
14         .build();
15 
16     Swagger2MarkupConverter.from(new URL("//localhost:8080/v2/api-docs?group=user"))  //url,注意埠號與分組
17         .withConfig(config)
18         .build()
19         .toFolder(Paths.get("src/docs/markdown/generated"));                //生成文件的存放路徑,生成多個文件
20 }

此時在src/docs/markdown/generated目錄下就會生成definitions.md、overview.md、paths.md、security.md文件,即生成的markdown文件

generateMarkdownDocsToFile()

 1 /**
 2  * 生成Markdown格式文檔,並匯總成一個文件
 3  * @throws Exception
 4  */
 5 @Test
 6 public void generateMarkdownDocsToFile() throws Exception {
 7     //    輸出Markdown到單文件
 8     Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
 9         .withMarkupLanguage(MarkupLanguage.MARKDOWN)    //輸出格式:ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10         .withOutputLanguage(Language.ZH)                //語言類型:中文(ZH) 默認英文(EN)
11         .withPathsGroupedBy(GroupBy.TAGS)                //Api排序規則
12         .withGeneratedExamples()
13         .withoutInlineSchema()
14         .build();
15 
16     Swagger2MarkupConverter.from(new URL("//localhost:8080/v2/api-docs?group=user"))    //url,注意埠號與分組
17         .withConfig(config)
18         .build()
19         .toFile(Paths.get("src/docs/markdown/generated/all"));                 //生成文件的存放路徑,匯總為一個文件
20 }

此時在src/docs/markdown/generated目錄下就會生成all.md文件,即生成的markdown文件

注意:

  • 如果在Swagger2Config類里聲明了分組,即Docket方法有.groupName(“user”),那麼測試方法中url路徑後面需要添加?group=user。如果Swagger2Config類中未聲明分組,則測試方法中url路徑不需要添加?group=user

  • 在使用測試方法生成文件的時候需要關閉項目,否則會提示埠被佔用

  • 可以修改Swagger2MarkupConfig.withMarkupLanguage()方法內的參數值來生成不同的文件格式,修改Swagger2MarkupConverter.toFile()方法內的參數值提供對應的生成文件存放路徑

  • definitions.md存放Models相關資訊,overview.md存放文檔概覽相關資訊,paths.md存放controller相關資訊,security.md存放與身份認證相關的資訊

4、導出文檔部分內容

all.md

 

Tags: