swagger是一个可以生成API文档的工具,同时可以进行API的在线测试调用。在项目中有使用到,感觉用起来非常方便,是一个比较好用的工具。这篇文章简单介绍下给SpringBoot项目接入swagger,能够满足基本的接口文档查询和手工调试。
添加依赖
项目使用maven管理,添加如下的两个依赖就可以了。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
启用配置
这部分是在项目中添加configuration配置,用来加载swagger
@Configuration
@EnableSwagger2
@Profile(value = {"staging", "development"})
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(basePackage("com.xxxxx.controller"))
.paths(any())
.build();
}
}
注意需要设置的basePackage,是controller的引用包目录,profile设置developement,staging,一般不建议在线上开启。这样就完成了,看起来很简单,后面我们再看下效果。其他比较复杂的功能可以访问swagger的官网深入了解。
使用
启动项目,注意swagger访问地址是服务ip+配置的context-path + swagger-ui.html
,首先看下效果图,很清楚得展示了接口和参数:

同时可以做手工调试:

可以看到确实是一个简单好用的工具。
网友评论