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、页面效果

http://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("http://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("http://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

GitHub地址:https://github.com/HuskySir/JAVA/tree/master/Swagger

posted @ 2021-05-24 19:49  HuskySir  阅读(1766)  评论(0编辑  收藏  举报