经手的项目几乎都是前后端分离的,就牵涉到api接口定义和文档维护的问题。用过gitlab,也用过confluence,缺点很明显,接口一有改动,文档就要响应做更新,很多时候都是接口改了,文档还停留在最初的那个版本,久而久之就很难根据文档来定位问题,遇到问题就不得不去翻代码。
久闻Swagger能解决这个问题,以前从未使用,最近有看了一些文档,就把入门的步骤记录下来。
背景:项目是用Springboot搭的,maven做依赖管理。
1,添加maven依赖
<!--swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Swagger会依赖guava,开始项目里引入的guava版本是14.0的,项目启动时会报如下错:

升级guava版本如下:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
2,增加配置
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @date : 2021--06--01
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//指定要生成api接口的包路径 就是controller包路径
.apis(RequestHandlerSelectors.basePackage("com.ryan.dailytest.controller"))
.paths(PathSelectors.any())
.build();
}
//指定要构建的api的详细信息
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("springboot集成swagger2接口")
.description("学习swagger2")
.contact("Ryan:xxx@jd.com")
.version("1.0")
.build();
}
}
3,启动项目 访问:localhost:{port}/swagger-ui.html

红色圈注的是项目里两个controller,对应界面上两个条目
点击可以看到controller下的所有接口

再点击展开,可以进行模拟调用

前后端分离项目存在API接口定义和文档维护难题,GitLab和Confluence使用时接口改动后文档更新不及时。作者以Spring Boot项目为例,记录了Swagger入门步骤,包括添加Maven依赖、增加配置、启动项目并访问特定页面进行接口模拟调用等。
1586

被折叠的 条评论
为什么被折叠?



