Swagger 框架是目前最主流的自动生成接口文档框架之一,学会他的使用对我们的项目开发工作有着极大的好处。
使用使用swagger框架的方式
1. 添加依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
在pom.xml文件中增加上述依赖
2.添加配置
在yml文件中加入
# swagger接口文档配置
swagger2:
title: RBAC项目RESTful API
description: 开发人员太懒,没有写描述
version: 1.0
contactName: wangchen
contactEmail:
contactUrl:
basePackageRest: com.qcby.demo.controller
termsOfServiceUrl:
basePackageRest 对应内容填写controller包地址 ,需要的话contactEmail中也可以填自己的邮箱
创建SwaggerProperties类
内容为
@Data
//Component注解 将该组件交给Spring boot来管理
@Component
@ConfigurationProperties(prefix = "swagger2")
public class SwaggerProperties {
private String title;
private String contactName;
private String contactUrl;
private String contactEmail;
private String version;
private String description;
private String basePackageRest;
private String termsOfServiceUrl;
}
该类与配置文件中的内容一一对应
创建SwaggerConfig类对接口文档进行配置
内容
@Configuration
// springboot 集成swagger2开关
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("REST接口")
.apiInfo(apiInfo())
.select()
// 配置自动扫描那些包下类型生成接口文档
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackageRest()))
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(),swaggerProperties.getContactEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
}
// 类
@Api(value = "通用接口", tags = {"通用接口"})
// 参数
@ApiImplicitParams(
{@ApiImplicitParam(name = "Authorization",
value = "Authorization token", required = true,
dataType = "string", paramType = "header")}
)
// 实体类字段
@ApiModelProperty(value = "创建时间")
可利用上述注释分别对类,参数,实体类字段进行设置
·如设置拦截器需要对
"/swagger-resources/**"
,"/webjars/**"
,"/v2/**"
,"/swagger-ui.html/**"
路径放行
然后我们就可以访问到接口文档了
启动项目
访问http://localhost:8080/swagger-ui.html
可以看到
版权声明:本文为qq_51088445原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。