Swagger2简介
Swagger2可以轻松的整合到Spring Boot 中,并与Spring MVC程序配合组织出强大的RESTful API 文档。
它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。
Swagger2实现代码
添加Swagger2依赖
在pom.xml中添加Sqagger2依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
创建Swagger2配置类
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2的使用")
.description("Swagger2的使用")
.termsOfServiceUrl("https://me.csdn.net/weixin_43978477")
.contact("四季豆昂首")
.version("1.0")
.build();
}
}
@Configuration:让Spring加载该类配置
@EnableSwagger2:用来启用Swagger2
- 再通过createRestApi函数创建Docket的Bean之后,
- apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
- select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
添加到文档使用
通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。
@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response =“接口返回参数类型”, notes = “接口发布说明”) 其他参数可参考源码;
@ApiOperation(value="创建用户", notes="根据User对象创建用户", httpMethod = "POST")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
转自:https://www.jianshu.com/p/8033ef83a8ed