swagger
- 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
- 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。
添加依赖
<!--swagger2 start -->
<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>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.5</version>
</dependency>
<!--swagger2 end -->
添加配置类
这里把swagger配置单独写成一个类,如果把配置写在spring配置文件中,spring配置文件的内容会非常多。
@Configuration
@EnableSwagger2
public class Swagger2 {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
//创建一个bean
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径 com.etc.demo 控制器所在的包
.apis(RequestHandlerSelectors.basePackage("com.etc.controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring MVC 测试使用 Swagger2 构建RESTful API")
//创建人
.contact(new Contact("小白", "http://zretc.net", ""))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
在controller写标签
控制器类前:
@Api(value=“商品控制器”)
控制器接口方法前:
@ApiOperation(value=“商品列表”, httpMethod=“GET”,notes=“商品模糊查询”,response=AjaxResponse.class)
参数位置:
@ApiParam(name = “keywords”, required = false, value = “查询关键字”)
访问地址
http://localhost:8800/项目名/swagger-ui.html