Swagger2 可以动态生成Api接口文档,并且提供测试接口,降低沟通成本,促进项目高效开发。
一、swagger2的相关依赖
<!--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>
二、创建Swagger2配置类
@Configuration注解,让Spring来加载该类配置。
@EnableSwagger2注解来启用Swagger2。
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
//apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)
.apiInfo(apiInfo())
//select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现
.select()
//该包下的controller类生成api文档(除了被@ApiIgnore指定的请求)
.apis(RequestHandlerSelectors.basePackage("com.funnee.security"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Restful API")
.description("Funnee's swagger")
.termsOfServiceUrl("http://localhost:8080")
.version("1.0")
.build();
}
}
三、swagger2的访问地址
swagger2的默认访问地址为:URL(当前项目)/swagger-ui.html
swagger2的访问地址和页面也可自定义:
-
把swagger的项目目录拷贝到本地项目;
-
新增配置文件,添加配置项
springfox.documentation.swagger.v2.path = swagger本地项目的路径
-
自定义页面
四、swagger2的文档说明相关注解
@Api 用于类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源
示例:@Api(value = "xxx", description = "xxx")
@ApiOperation 用于方法上,说明方法的作用,每一个url资源的定义
示例: @ApiOperation(value = "xxx",httpMethod="POST", notes= "xxx",response=String.class)
@ApiParam 用于方法、参数、字段上,请求属性
示例: public List<User> addUser(@RequestBody @ApiParam(value = "user object", required = true) User user)
@ApiImplicitParams 用于方法上,包含一组参数说明
@ApiImplicitParam 用于方法上,用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
@ApiResponse 用于方法上,响应配置
示例:@ApiResponse(code = 400, message = "Invalid user supplied")
@ApiResponses 用于方法上,响应配置集合
示例:@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
@ApiIgnore 用于类,属性,方法上,忽略某项api,使用@ApiIgnore
示例代码:
@RestController
@RequestMapping("/user")
@Api(value = "用户查询接口", description = "用户查询接口")
public class UserController {
@GetMapping
@JsonView(User.UserSimpleView.class)
@ApiOperation(value = "根据条件查询用户信息",notes = "查询用户信息")
@ApiImplicitParams({@ApiImplicitParam(name = "page",value = "每页大小"),@ApiImplicitParam(name="name",value = "用户姓名")})
public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page = 2,size = 10,sort = {"name,asc","age,desc"}) Pageable pageable){
//...
}
}
在swagger2中的效果图:
五、swagger代码生成器
Swagger Codegen是一个开源的代码生成器,根据Swagger定义的RESTful API可以自动生成建立服务端和客户端的连接的api代码。
GitHub: https://github.com/swagger-api/swagger-codegen