前言
整合Swagger2文档API;优化Swagger2显示。
文章目录
一、整合Swagger2文档API
为了减少程序员撰写文档时间,提高生产力, Swagger2 应运而生,使用 Swagger2可以减少编写过多的文档,只需要通过代码就能生成文档API,提供给前端人员对接,非常方便。
1.1 在pom文件中引入swagger2配置依赖
<!-- swagger2 配置 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.6</version>
</dependency>
1.2 编写Swagger2配置类
package com.imooc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableSwagger2
public class Swagger2 {
// http://localhost:8088/swagger-ui.html 原路径
// http://localhost:8088/doc.html 原路径
// 配置swagger2核心配置 docket
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
.apiInfo(apiInfo()) // 用于定义api文档汇总信息
.select()
.apis(RequestHandlerSelectors
.basePackage("com.imooc.controller")) // 指定controller包
.paths(PathSelectors.any()) // 所有controller
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("天天吃货 电商平台接口api") // 文档页标题
.contact(new Contact("imooc",
"https://www.imooc.com",
"abc@imooc.com")) // 联系人信息
.description("专为天天吃货提供的api文档") // 详细信息
.version("1.0.1") // 文档版本号
.termsOfServiceUrl("https://www.imooc.com") // 网站地址
.build();
}
}
1.3 Swagger2的常用注解说明
@ApiIgnore
此注解主要作用在方法上,类上,参数上。
当作用在方法上时,方法将被忽略;作用在类上时,整个类都会被忽略;作用在参数上时,单个具体的参数会被忽略。
@Api(value = “用途”, tags = {“说明”})
作用在类上,描述Controller的作用。若不使用则用类名作为类功能。
@ApiOperation(value = “用途”, notes = “说明”, httpMethod = “GET”)
作用在方法/接口上,描述这个方法的功能和注意事项。若不使用则用函数名作为方法功能。
@ApiModel(value = “用户对象BO”, description = “从客户端,由用户传入的数据封装在此entity中”)
作用在实体类上,可以描述这个类的功能。
@ApiModelProperty(value = “用户名”, name = “username”, example = “imooc”, required = true)
作用在实体类的属性上,可以描述这个属性的作用。
二、优化Swagger2显示
2.1 访问原生文档
访问未有优化前的文档,页面如图显示:http://localhost:8088/swagger-ui.html
2.1 访问优化后的文档
访问我们引入的UI优化后的文档:http://localhost:8088/doc.html
总结
整合Swagger2文档API;优化Swagger2显示。