- 本文主要介绍基于springboot框架下使用swagger生成api文档的基本使用方法
- 基于REST风格的接口接口规范来进行代码编写,加上自动化的api文档简直不要太舒服,下面是基本的使用,以及解释
- 在传统开发中我们经常使用word来进行接口文档的编写,这种方法很繁琐,随着时间的增加接口的变化和繁多也会导致文档变得难以维护和停止维护,这对于刚入职公司的新人来说是非常的不友好的,swagger可以根据你接口的参数变化随着你服务器的启动来进行不断的更新文档;
- 首先需要搭建一个springboot的项目,此处省略;
- pom依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
- swagger的配置相当简单,需要作为一个配置类来进行加载,以下为代码
package com.sunyw.xyz.statics;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.builders.PathSelectors;
/**
* @description:swaggerAPI文档配置属性类
* @author: sunyw
* @time: 2020-02-25 13:13
*/
@Configuration
@EnableSwagger2
public class WeatherSwagger {
@Bean
public Docket createSwagger(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.sunyw.xyz"))
.paths(PathSelectors.regex("/api/.*"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Weather天气平台API文档")
.description("sunyw")
.termsOfServiceUrl("https://xxx.xyz")
.version("1.0")
.build();
}
}
- 然后重新启动项目,访问http://localhost:7000/swagger-ui.html
- 效果图
- swagger的测试平台,点开后面的接口即可进行接口测试
- 测试
- 有帮助的话帮忙点个👍